温馨提示×

Java的indexof有哪些替代方法

小樊
109
2024-07-11 21:13:28
栏目: 编程语言

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

0