如何使用 Java 在字串中查詢唯一字元?
您可以透過以下方式查詢給定字串是否包含指定的字元:
使用 indexOf() 方法
您可以使用 String 類的 indexOf() 方法在字串中搜索特定字母。此方法返回一個整數引數,該引數是字串中單詞的位置索引,或者如果給定字元在指定的字串中不存在,則返回 -1。
因此,要查詢特定字元是否存在於字串中:
透過將指定的字元作為引數傳遞給字串,呼叫字串上的 indexOf() 方法。
如果此方法的返回值不是 -1,則表示字串包含指定的字元。
示例
import java.util.Scanner;
public class IndexOfExample {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the required String: ");
String str = sc.next();
System.out.println("Enter the required character: ");
char ch = sc.next().toCharArray()[0];
//Invoking the index of method
int i = str.indexOf(ch);
if(i!=-1) {
System.out.println("Sting contains the specified character");
} else {
System.out.println("String doesn’t contain the specified character");
}
}
}輸出
Enter the required String: Tutorialspoint Enter the required character: t Sting contains the specified character
使用 toCharArray() 方法
String 類的 toCharArray() 方法將給定的字串轉換為字元陣列並返回它。
因此,要查詢特定字元是否存在於字串中:
將其轉換為字元陣列。
將陣列中的每個字元與所需的字元進行比較。
如果匹配,則字串包含所需的字元。
示例
import java.util.Scanner;
public class FindingCharacter {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the required String: ");
String str = sc.next();
System.out.println("Enter the required character: ");
char ch = sc.next().toCharArray()[0];
//Converting the String to char array
char charArray[] = str.toCharArray();
boolean flag = false;
for(int i = 0; i < charArray.length; i++) {
flag = true;
}
if(flag) {
System.out.println("Sting contains the specified character");
} else {
System.out.println("String doesnt conatin the specified character");
}
}
}輸出
Enter the required String: tutorialspoint Enter the required character: T Sting contains the specified character
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP