Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

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
SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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?
Avatar of gudii9

ASKER

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:"

please advise.

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.";
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.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
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()));

Open in new window

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"));
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;
}
Avatar of gudii9

ASKER

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
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
if (filename.lastIndexOf(".xls") < 0 {

why use lastIndexOf?
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.
>> 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.
Avatar of gudii9

ASKER

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
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.
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.
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.
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));
Avatar of gudii9

ASKER

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));

Open in new window

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?

Please advise
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)
If your string is
"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
>>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
Avatar of gudii9

ASKER

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

Above understanding is correct right? please advise
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>If my updated string is
"aabbzzzwexrweyyywexooo"
string.indexOf("wex",string.indexOf("wex",5)+2) -> string.indexOf("wex",9) -> 11
string.lastIndexOf("wex",16)  -> 11
Above understanding is correct right? please advise <<

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.
Avatar of gudii9

ASKER

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));
	}

	
}

Open in new window


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

Open in new window



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.

Please advise