# string indexOf method

Hi,

I am not very clear on indexOf method and its usage. When and where and how we use it. what are practical uses of it. Please provide some good practical examples on this. Thanks in advance
LVL 7
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Billing EngineerCommented:
starting with the "school" example:
http://www.w3schools.com/jsref/jsref_indexof.asp

the function returns the numerical index (starting at 0 when found at the beginning) of where the "sub"string is found (first) in the string you apply indexOf on.
This method returns -1 if the value to search for never occurs.
0
Commented:
Please provide some good practical examples on this
-

*Are* you serious? We covered indexOf many times already! Surely you can see from your very last question, as well as the "yak" challenge, how it works?
0
Author Commented:
yes. I thought of diving more deep into this concept

Example

Find the first occurrence of the letter "e" in a string, starting the search at position 5:

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("e",5);
The result of n will be:

14

based on the w3schools link i understand the output as 14. What is practical advantage of "Find the first occurrence of the letter "e" in a string, starting the search at position 5:"

Any way 14 is the index starting from the index 0 which is 'H' in below case
var str = "Hello world, welcome to the universe.";
0
Billing EngineerCommented:
this is not a concept you can really do any deep diving, in other terms: this is no rocket science.
just one of the low-level tools that you have just to know when doing something with texts and you need to check if there is some sequence of letters inside another (longer) sequence of letters.
0
Commented:
Right, well you have understood exactly what is going on there correctly. So the technical part seems to be much clearer for you.

The question you are then really asking here is more like "what use can I put this knowledge to".

To answer this, you need to have a problem to solve. So your problem could be anything to do with finding words or parts of words from any given text, or for example in lists of names, where you might have "Jones, Jeremiah, Mr." as can be common in some database records, and you want to get these entries back into some more conventional form, such as Mr. Jeremiah Jones, so you can address letters or whatever. In this case ((and this is just an example so it might not be a valuable real-world scenario), you can grab the surname by substring(0,indexOf(",") and begin to re-assemble your name. There are endless other - better - applications, some of which turn up regularly in ordinary programming, where the user might even input values that need to be converted for all sorts of reasons.
0
Commented:
What is practical advantage of "Find the first occurrence of the letter "e" in a string, starting the search at position 5:"
There's no practical reason for this example.  What they're explaining though is that "indexOf(pattern)" always returns the first occurrence of a pattern inside a string.

However, in many practical applications you want to find a point where the pattern occurs later in the string.  Not just the first occurrence.  So in that case you can use the "indexOf(pattern, startIndex)" method to start the search at "startIndex".

Now you have a very powerful tool that lets you find the first occurrence of "pattern", the 2nd occurrence etc. because you don't always have to start the search from position 0 in the string.

Make sense?

Doug
0
Commented:
And don't forget "lastIndexOf", which can locate the last appearance of a char or string within another string.

So although you can do this :

indexOf("x",lastIndexOf("x")+1)

it doesn't make any sense. Although it will still return a method-legal value.
0
Commented:
You can get a lot of fun out of experimenting yourself too, never mind online challenges. Try -

``````System.out.println("Ham"+"Porkburger".substring("hamburger".indexOf("burger","hamburger".lastIndexOf("burger","hamburger".indexOf("burger"))-"hamburger".indexOf("burger"))+1,"Porkburger".length()));
``````
0
Commented:
There is also the angle that with indexOf, you can test whether a string contains a certain substring, without calling contains(). This means that if you get a return value that is 0 or more, you know the substring is there - so you get a double-whammy, two results for the price of one - i.e the index and a "pseudo-Boolean".

System.out.println("hamburger".contains("burger"));
System.out.println("hamburger".indexOf("zurger"));
0
Commented:
I'll give you a common application of how I've often used lastIndexOf(). Assume I have a folder of files of different type (e.g. Word documents, Excel spreadsheets, CSV files, etc.) and all I want to do is manage the spreadsheets, I can do something like the following:
for (File filename : folder) {
if (filename.lastIndexOf(".xls") < 0 {
continue;
} else {
do something;
}
0
Author Commented:
Example

Find the first occurrence of the letter "e" in a string:

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("e");
The result of n will be:

1

Above method is already there right.

What additional advantage below method(with 2 arguments) has compared to above method(with one argument)

Example

Find the first occurrence of the letter "e" in a string, starting the search at position 5:

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("e",5);
The result of n will be:

14
0
Commented:
Here's an example of using the second parameter.
Suppose you have a directory structure with the following filepaths and just want to list the groups:
/home/group1/user/files
/home/group2/user/files
...
/home/groupN/user/files

for (String path : filepaths) {
//The following gets the substring of the path starting at the first slash after the second character
String newPath = path.substring(path.indexOf("/",1));
//The following gets the substring of the newPath starting at the second character up to the second slash
String group = newPath.substring(1, newPath.indexOf("/",1));
System.out.println(group);
}
0

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
if (filename.lastIndexOf(".xls") < 0 {

why use lastIndexOf?
0
Commented:
Perhaps there was an expectation that it would be faster than indexOf when the substring to search for seems more likely to appear near the end of filename than near the beginning.

If ".xls" appears in multiple places within filename then lastIndexOf rather than indexOf could be a way of specifying which index was desired, but since only < 0 is being tested here there would be no functional difference for this purpose.
0
Commented:
>> there would be no functional difference <<

exactly, and so posting a comment that appears to suggest there is a difference, is not really very helpful.

It would also be a bad idea to run a filenaming convention on the premise that it's ok to include the type in the body - it's anyway a tautology.
0
Author Commented:
Find the first occurrence of the letter "e" in a string, starting the search at position 5:

var str = "Hello world, welcome to the universe.";
var n = str.indexOf("e",5);
The result of n will be:

14

can i find last occurrence of letter "e" in a string starting the search at position 5 or
can i find second occurrence of letter "e" in a string starting the search at position 5
or
can i find first occurrence of group of letter "we" in a string starting the search at position 5
or
can i find second occurrence of group of letter "we" in a string starting the search at position 5
0
Commented:
1) can i find last occurrence of letter "e" in a string starting the search at position 5 - No
2) can i find second occurrence of letter "e" in a string starting the search at position 5 - No
3) can i find first occurrence of group of letter "we" in a string starting the search at position 5 - Yes
4) can i find second occurrence of group of letter "we" in a string starting the search at position 5 - No

indexOf will always return the index of whatever the search string is that immediately follows the starting position (or -1 if not found), as such, using your example string "Hello world, welcome to the universe." The indexes of "e" are at positions 1, 14, 19,  26, 32, and 35 and the only index of "we" is at 13.

1)  Starting at position 5, the only index returned will be 14. You would not get the last index of "e" if the starting position where anywhere between 2 and 32 and only get the last index by luck starting with 33-35. To get the last index, use lastIndexOf().
2) To get the second occurrence of the index of "e" you can't use str.indexOf("e",5) that would be 14 and not 19. You could nest them, however, by using str.indexOf("e",indexOf(str.indexOf("e",5) + 1)
3) You will get index of the first occurence of the String "we" using str.indexOf("we",5). You would also get that using any starting position from 0 to 13.
4) Just like 2) above you can't use the same starting position as that which returns the index of the first occurrence but you can again nest them in similar fashion. If this case, of course, a -1 would be returned as there is no second occurrence.
0
Commented:
I kinda can't help here any longer - again, we've covered and recovered the points and mechanisms from every possible angle, and the best thing you can do is look up the API and the indexOf() method, and just understand and accept its syntax.

But to save you the trouble, here it is as my last comment on this :

int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.

int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.

int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

. . .  and here is lastIndexOf() :

int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.

int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

int lastIndexOf(String str)
Returns the index within this string of the last occurrence of the specified substring.

int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
0
Commented:
BTW, you shouldn't refer to the letter "e" or the group of letter "we". Anything inside double quotes is going to be a String. Note searching on the letter e could either be 'e' or "e" since indexOf takes either a char or a String as a parameter.
0
Commented:
can i find last occurrence of letter "e" in a string starting the search at position 5
// if you mean find rightmost occurrence of letter "e" starting the search at position 5 and searching positions to the left of position 5
System.out.println(string.lastIndexOf("e",5));
// if you mean find rightmost occurrence of letter "e" starting the search at position 5 and searching positions to the right of position 5
x = string.indexOf("e",5);

can i find second occurrence of letter "e" in a string starting the search at position 5
System.out.println(string.indexOf("e",string.indexOf("e",5)+1));

//
can i find first occurrence of group of letter "we" in a string starting the search at position 5
System.out.println(string.indexOf("we",5));

can i find second occurrence of group of letter "we" in a string starting the search at position 5
System.out.println(string.indexOf("we",string.indexOf("we",5)+1));
0
Author Commented:
int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

what is meaning of searching back wards.

BTW, you shouldn't refer to the letter "e" or the group of letter "we".

Can you please elaborate on this.

anything inside double quotes is going to be a String. Note searching on the letter e could either be 'e' or "e" since indexOf takes either a char or a String as a parameter.

which one is preferred 'e' or "e" in case of single character string like this.
``````System.out.println(string.indexOf("we",string.indexOf("we",5)+1));
``````
what is meaning of +1 above. If my string is as below
"aabbzzzwerrweyyyweoooo"

string.indexOf("we",5) is 7 right(since after index 5 "we" first occured at 7
if we say

string.indexOf("we",7+1))-->
string.indexOf("we",8)) which is 11 right?

0
Commented:
what is meaning of searching back wards.
It means find the largest index where specified target is found. (or -1 if it is not found)

string.indexOf("we",string.indexOf("we",5)+1)
"aabbzzzwerrweyyyweoooo"
string.indexOf("we",5) -> 7
string.indexOf("we",5)+1 -> 7+1 -> 8
string.indexOf("we",string.indexOf("we",5)+1) -> string.indexOf("we",8) -> 11
without the +1
string.indexOf("we",string.indexOf("we",5)) -> string.indexOf("we",7) -> 7
0
Commented:
>>what is meaning of searching back wards.<<
Basically it means searching from the end of the string or from some index backwards.
Using ozo's example string -
string.lastIndexOf("we")  or string.lastIndexOf("we",string.length()) -> 16
string.lastIndexOf("we",16)  -> 11
string.lastIndexOf("we",11)  -> 7
string.lastIndexOf("we",7)  -> -1
0
Author Commented:
If my updated string is
"aabbzzzwexrweyyywexooo"

string.indexOf("wex",string.indexOf("wex",5)+2) -> string.indexOf("wex",9) -> 11

string.lastIndexOf("wex",16)  -> 11

string.lastIndexOf("wex",11)  -> 7
string.lastIndexOf("wex",7)  -> -1

0
Commented:
You don't need to wait for us to answer questions like that if you can ask your Java compiler:
String string="aabbzzzwexrweyyywexooo";
System.out.println("string.indexOf(\"wex\",5) -> " + string.indexOf("wex",5));
System.out.println("string.indexOf(\"wex\",9) -> " + string.indexOf("wex",9));
System.out.println("string.indexOf(\"wex\",string.indexOf(\"wex\",5)+2) -> " + string.indexOf("wex",string.indexOf("wex",5)+2) );
System.out.println("string.lastIndexOf(\"wex\",16)  ->  " + string.lastIndexOf("wex",16));
System.out.println("string.lastIndexOf(\"wex\",11)  -> " + string.lastIndexOf("wex",11));
System.out.println("string.lastIndexOf(\"wex\",7)  -> " + string.lastIndexOf("wex",7));
0
Commented:
>>If my updated string is
"aabbzzzwexrweyyywexooo"
string.indexOf("wex",string.indexOf("wex",5)+2) -> string.indexOf("wex",9) -> 11
string.lastIndexOf("wex",16)  -> 11

No. The only two indexes of "wex" are 7 and 16. So any search for indexOf starting anywhere from 0 to 7 will produce 7 and starting anywhere from 8 to 16 will produce 16 and starting anywhere from greater than 16 will prduce -1. Likewise,any search for lastIndexOf starting anywhere from 0 to 6 will produce -1 and starting anywhere from 7 to 15 will produce 7 and starting anywhere greater than 16 will prduce 16.
0
Author Commented:
Likewise,any search for lastIndexOf starting anywhere from 0 to 6 will produce -1 and starting anywhere from 7 to 15 will produce 7 and starting anywhere greater than 16 will prduce 16.

can you please elaborate on this.

``````public class Test35 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

String string="aabbzzzwexrweyyywexooo";//wex is at index 7 and 16
System.out.println("string.indexOf(\"wex\",5) -> " + string.indexOf("wex",5));
System.out.println("string.indexOf(\"wex\",9) -> " + string.indexOf("wex",9));
System.out.println("string.indexOf(\"wex\",string.indexOf(\"wex\",5)+2) -> " + string.indexOf("wex",string.indexOf("wex",5)+2) );
System.out.println("string.lastIndexOf(\"wex\",16)  ->  " + string.lastIndexOf("wex",16));
System.out.println("string.lastIndexOf(\"wex\",11)  -> " + string.lastIndexOf("wex",11));
System.out.println("string.lastIndexOf(\"wex\",7)  -> " + string.lastIndexOf("wex",7));
System.out.println("string.lastIndexOf(\"wex\",15)  -> " + string.lastIndexOf("wex",15));
System.out.println("string.lastIndexOf(\"wex\",17)  -> " + string.lastIndexOf("wex",17));
}

}
``````

when i run as above i got different results as below

``````string.indexOf("wex",5) -> 7
string.indexOf("wex",9) -> 16
string.indexOf("wex",string.indexOf("wex",5)+2) -> 16
string.lastIndexOf("wex",16)  ->  16
string.lastIndexOf("wex",11)  -> 7
string.lastIndexOf("wex",7)  -> 7
string.lastIndexOf("wex",15)  -> 7
string.lastIndexOf("wex",17)  -> 16
``````

string.lastIndexOf("wex",17)  -> 16 //this did not produce -1

It means find the largest index where specified target is found. (or -1 if it is not found)

so if string is
aabbzzzwexrweyyywexooo

start searching from o then o then o then x then e then w like that right.

Does in this case index supposed to be backwards too?
like o(index 0) and o(index 1) and o(index 2) and x(index 3)
or index goes as usual

like a(index 0) and a(index 1) and b(index 2) and b(index 3)

i understand clearly indexOf() but lastIndexOf() still not very clear.