开发者

How to Use Indexof()method in java

开发者 https://www.devze.com 2023-03-22 21:28 出处:网络
I am using indexof() for finding a sub string. It finds my string if my string is not on first position, if my string is at the first location it won\'t work. Can any one suggest another way to find i

I am using indexof() for finding a sub string. It finds my string if my string is not on first position, if my string is at the first location it won't work. Can any one suggest another way to find it?

Here is My Code:-

public class IndexOfStr {


  public static void main(String args[]) {
  String s = "Niraj";
  System.out.println(s);
  System.out.println("indexOf(niraj, 1) -> " + s.indexOf("niraj", 1));


 }}

Output:-

Niraj indexOf(niraj, 1) -> -1

I am trying to to find the string in 开发者_开发问答my Excel file.


The first character in a strings is at index 0, not index 1.

Do also note that indexOf is case sensitive.

I don't know how you have access to the data in the Excel file, but you probably want to either convert all data to lower case when you search for a match, or use regexp when searching, and make the regexp case insensitive.


from docs:

Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. The integer returned is the smallest value k for which: k >= Math.min(fromIndex, this.length()) && this.startsWith(str, k) If no such value of k exists, then -1 is returned.

You started from index 1 instead of index 0, so the string was not found.

You can do either s.indexOf("niraj", 0) or s.indexOf("niraj")


You should start from 0 rather than 1.

s.indexOf("Niraj", 0);

and please keep in mind that indexOf() method is case-sensitive.


Two errors occur here:
1) Your string is "Niraj", and you would like to find substring "niraj". Therefore, your substring does not exist in the given string and you get -1.
2) You start searching at position 1, not position 0, therefore your substring is not in the given range. Either enter correct substring or call

s.toLowerCase().indexOf("niraj", 0)

0

精彩评论

暂无评论...
验证码 换一张
取 消