0

I am trying to figure out how to search a string for a certain number then if that number exists in the string do the following:

String str = "String4";
int myInt = 0;
public static void checkString(String str)  // FIX ME
{
    if(str.indexOf('3') == 0)
    {
        myInt = 3;
    }
    else if(str.indexOf('4') == 0)
    {
        myInt = 4;
    }
    else if(str.indexOf('5') == 0)
    {
        myInt = 5;
    }
}

This never returns true though, is there an alternative way to search the string. There is a lot of extra code, but this method is the only thing causing the problem. I am pulling my hair out because of it, some help would be much appreciated!

Mike G
  • 4,142
  • 9
  • 43
  • 64
  • 3
    indexOf() returns the _index_ of that character. 0 is the first character. In your example, indexOf('4') will return 6, since '4' is the seventh character in that string (starting with counting at 0) – httpdigest Feb 25 '19 at 20:19
  • 2
    Try using string.contains('4') instead – Talik Feb 25 '19 at 20:20
  • Alternatively, have a look at: https://stackoverflow.com/questions/2367381/how-to-extract-numbers-from-a-string-and-get-an-array-of-ints how to use regular expression to extract the number(s) in a string. Probably better than having a switch-case/if-statement for every digit/number, especially when your numbers can have multiple digits. – httpdigest Feb 25 '19 at 20:26
  • do you know the `integer` you're searching for before-hand? – molamk Feb 25 '19 at 20:35

3 Answers3

1

For example

if(str.indexOf('3') == 0) 

search everytime 3 at position 0, it's not appropriate, because digit can be everywhere in string.

Use instead

str.indexOf('3')!=-1 

and retrieve position with return value of indexOf

nissim abehcera
  • 781
  • 5
  • 7
1

Check if a substring is in the given string using the contains method.

public static void checkString(String str)
{
    if(str.contains("3"))
        myInt = 3;
    else if(str.contains("4"))
        myInt = 4;
    else if(str.contains("5"))
        myInt = 5;
}
Rohan
  • 349
  • 2
  • 15
1

Let's start with an explanation of your approach before we get to an answer.

Starting with your string String str = "String4", I'm assuming that you pass it to checkString().

The indexOf() function for a string searches the string for a substring (a character in your case) and returns its position, indexed from 0. For example, if you call str.indexOf("t") it will return 1 because the character t is in position 1. Therefore, in your code you check if the numbers 3, 4, and 5 reside in the strings index 0 (the first character).

If you want to use indexOf() for this function, you can check if the number is in the string in the first place. IndexOf() returns -1 if the character your searching for isn't in the string, so you can use the following:

if (str.indexOf("3") != -1){
    //do your stuff
}

And the same for 4 and 5.

Logan Rodie
  • 615
  • 4
  • 12