Java的indexof有哪些替代方法

avatar
作者
筋斗云
阅读量:13

  1. 使用String的contains方法结合indexOf方法来实现查找功能:
String str = "Hello World"; if(str.contains("World")){     int index = str.indexOf("World");     System.out.println("Index of 'World': " + index); } else {     System.out.println("'World' not found"); } 
  1. 使用String的charAt方法和循环来实现查找功能:
String str = "Hello World"; char target = 'W'; int index = -1; for(int i=0; i<str.length(); i++){     if(str.charAt(i) == target){         index = i;         break;     } } System.out.println("Index of 'W': " + index); 
  1. 使用String的toCharArray方法和循环来实现查找功能:
String str = "Hello World"; char[] charArray = str.toCharArray(); char target = 'W'; int index = -1; for(int i=0; i<charArray.length; i++){     if(charArray[i] == target){         index = i;         break;     } } System.out.println("Index of 'W': " + index); 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!