indexof method:
Note: The indexOf method returns an integer value indicating the starting position of the substring within the String object. If the substring is not found, -1 is returned.
public class IndexOf{ public static void main(String[] args){ String s="李宏#王海#林巧#陆寻#唐梅"; String q="#"; //需要查找的字符串 String err="*"; //不存在的字符串 int i=0; for(int j=0;j<s.length();j++){ //循环所有字符串 String get=s.substring(j,j+1); //打印所有字符串 if(get.equals(q)){ //判断#字是否出现 i++; //#字出现次数 } } System.out.println("总共有"+s.length()+"个字符串"); System.out.println("#字共出现了"+i+"次"); //#字符总共出现的次数 System.out.println("第一个#字出现在字符串的"+s.indexOf(q)+"个位置"); if(s.indexOf(err)==-1){ //返回-1则表示字符不存在字符串中 System.out.println("*字在字符串中不存在"); } } }
Run results:
There are 14 strings in total.
# words appear 4 times in total.
The first # word appears in 2 of the strings. The word at position
* does not exist in the string
The above is the detailed content of What is the use of indexof method in java. For more information, please follow other related articles on the PHP Chinese website!