ในการค้นหาอักขระที่ไม่ซ้ำตัวแรกจากสตรีมของอักขระ โค้ด Java มีดังต่อไปนี้ −
ตัวอย่าง
import java.util.ArrayList;
import java.util.List;
public class Demo{
final static int max_chars = 256;
static void non_repeating_char(){
List<Character> my_list = new ArrayList<Character>();
boolean[] repeat = new boolean[max_chars];
String my_str = "Thisisasample";
for (int i = 0; i < my_str.length(); i++){
char x = my_str.charAt(i);
if (!repeat[x]){
if (!(my_list.contains(x))){
my_list.add(x);
}
else{
my_list.remove((Character)x);
repeat[x] = true;
}
}
if (my_list.size() != 0){
System.out.print("The first non-repeating character of the string is ");
System.out.println(my_list.get(0));
}
}
}
public static void main(String[] args){
non_repeating_char();
}
} ผลลัพธ์
The first non-repeating character of the string is T The first non-repeating character of the string is T The first non-repeating character of the string is T The first non-repeating character of the string is T The first non-repeating character of the string is T The first non-repeating character of the string is T The first non-repeating character of the string is T The first non-repeating character of the string is T The first non-repeating character of the string is T The first non-repeating character of the string is T The first non-repeating character of the string is T The first non-repeating character of the string is T The first non-repeating character of the string is T
คลาสชื่อ Demo มีฟังก์ชันชื่อ 'non_repeating_char' รายการถูกสร้างขึ้นและมีการกำหนดสตริง สตริงนี้มีการวนซ้ำ และมีการตรวจสอบทุกอักขระ และการนับจะถูกจัดเก็บไว้ในรูปแบบของตัวแปรบูลีนในอาร์เรย์ชื่อ 'ทำซ้ำ' ค่าจะเป็นจริงหากมีการทำซ้ำและเป็นเท็จ ในฟังก์ชันหลัก ฟังก์ชันจะถูกเรียกใช้ และข้อความที่เกี่ยวข้องจะแสดงบนคอนโซล