บทความนี้สาธิตวิธีตรวจสอบว่าสตริงมีตัวอักษรที่กำหนดหรือไม่ (ไม่ใช่ "unique character" ตามความหมายทั่วไป)
วิธีที่ 1: ใช้ indexOf()
indexOf(char) คืนค่า index แรกที่เจอ หรือ -1 หากไม่เจอ
import java.util.Scanner;
public class FindCharacterIndexOf {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter string: ");
String str = sc.next();
System.out.println("Enter character to find: ");
char ch = sc.next().charAt(0);
int index = str.indexOf(ch);
if (index != -1) {
System.out.println("Found at index: " + index);
} else {
System.out.println("Character not found");
}
}
}
ผลลัพธ์
Enter string: Tutorialspoint
Enter character to find: t
Found at index: 0
วิธีที่ 2: ใช้ toCharArray() + Loop
import java.util.Scanner;
public class FindCharacterArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter string: ");
String str = sc.next();
System.out.println("Enter character: ");
char ch = sc.next().charAt(0);
char[] arr = str.toCharArray();
boolean found = false;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == ch) {
found = true;
break;
}
}
System.out.println(found ? "Found" : "Not found");
}
}
หาตัวอักษรที่ "ไม่ซ้ำ" จริงๆ (Unique Characters - ปรากฏ 1 ครั้ง)
หากต้องการหาตัวอักษรที่ปรากฏในสตริง เพียงครั้งเดียว:
วิธีที่ 1: ใช้ Frequency Map
import java.util.*;
public class UniqueCharacters {
public static void main(String[] args) {
String str = "programming";
// นับความถี่
Map freq = new LinkedHashMap<>();
for (char ch : str.toCharArray()) {
freq.put(ch, freq.getOrDefault(ch, 0) + 1);
}
// แสดงตัวอักษรที่มี freq = 1
System.out.print("Unique chars: ");
for (Map.Entry entry : freq.entrySet()) {
if (entry.getValue() == 1) {
System.out.print(entry.getKey() + " ");
}
}
// Output: p o a i n (r,g,m ซ้ำ)
}
}
วิธีที่ 2: ใช้ Stream API (Java 8+)
String str = "programming";
String unique = str.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(c -> c, LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Map.Entry::getKey)
.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(unique); // "poain"
วิธีที่ 3: ใช้ indexOf/lastIndexOf (Simple)
String str = "programming";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (str.indexOf(ch) == str.lastIndexOf(ch)) {
System.out.print(ch + " "); // ปรากฏครั้งเดียว
}
}
สรุป
| เป้าหมาย | เมธอดที่แนะนำ |
|---|---|
| เช็คว่ามีตัวอักษร X หรือไม่ | str.indexOf(ch) != -1 |
| หา index แรกของ X | str.indexOf(ch) |
| หา index ทุกตัวของ X | Loop + indexOf(ch, fromIndex) |
| หาตัวอักษรที่ไม่ซ้ำ (unique) | Frequency Map หรือ indexOf == lastIndexOf |