溫馨提示×

Java的indexof有哪些替代方法

小樊
84
2024-07-11 21:13:28
欄目: 編程語言

  1. 使用String的contains方法結(jié)合indexOf方法來實現(xiàn)查找功能:
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方法和循環(huán)來實現(xiàn)查找功能:
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方法和循環(huán)來實現(xiàn)查找功能:
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