ในบทความนี้ เราจะทำความเข้าใจวิธีเปรียบเทียบสองสตริง การเปรียบเทียบระหว่างสองสตริงสามารถทำได้โดยใช้ตัวดำเนินการเลขคณิต '==' สตริงคือลำดับของอักขระ ในภาษาการเขียนโปรแกรม Java สตริงถือเป็นอ็อบเจ็กต์
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
สมมติว่าข้อมูลที่เราป้อนคือ −
Second string : Java Program First string :Java
ผลลัพธ์ที่ต้องการจะเป็น −
The result of string comparison is: 8
อัลกอริทึม
Step 1 - START Step 2 - Declare namely Step 3 - Define the values. Step 4 - Compute the lengths of the strings. Find the minimum of this length. Assign it to a variable. Step 5 - Iterate though this value and find the character at every index in both the strings. Convert them to integer, and compare these characters. Step 6 - Find the integer difference between these characters and return it as the output. Step 7 - Display the result Step 8 - Stop
ตัวอย่างที่ 1
ที่นี่ เราเชื่อมโยงการดำเนินการทั้งหมดเข้าด้วยกันภายใต้ฟังก์ชัน 'หลัก'
public class CompareStrings {
public static void main(String args[]) {
String input_string_1 = new String("Java Program");
System.out.println("The string is defined as: " +input_string_1);
String input_string_2 = new String("Java");
System.out.println("The string is defined as: " +input_string_2);
int length_1 = input_string_1.length();
int length_2 = input_string_2.length();
int minimum_length = Math.min(length_1, length_2);
int result;
for (int i = 0; i < minimum_length; i++) {
int character_1 = (int)input_string_1.charAt(i);
int character_2 = (int)input_string_2.charAt(i);
if (character_1 != character_2) {
result = character_1 - character_2;
}
}
if (length_1 != length_2) {
result = length_1 - length_2;
} else {
result = 0;
}
System.out.println("\nThe result of string comparison is: " +result);
}
} ผลลัพธ์
The string is defined as: Java Program The string is defined as: Java The result of string comparison is: 8
ตัวอย่างที่ 2
ในที่นี้ เราสรุปการดำเนินการเป็นฟังก์ชันที่แสดงการเขียนโปรแกรมเชิงวัตถุ
public class CompareStrings {
public static int string_compare(String input_string_1, String input_string_2) {
int length_1 = input_string_1.length();
int length_2 = input_string_2.length();
int minimum_length = Math.min(length_1, length_2);
for (int i = 0; i < minimum_length; i++) {
int character_1 = (int)input_string_1.charAt(i);
int character_2 = (int)input_string_2.charAt(i);
if (character_1 != character_2) {
return character_1 - character_2;
}
}
if (length_1 != length_2) {
return length_1 - length_2;
} else {
return 0;
}
}
public static void main(String args[]) {
String input_string_1 = new String("Java Program");
System.out.println("The string is defined as: " +input_string_1);
String input_string_2 = new String("Java");
System.out.println("The string is defined as: " +input_string_2);
System.out.println("\nThe result of string comparison is: " +string_compare(input_string_1, input_string_2));
}
} ผลลัพธ์
The string is defined as: Java Program The string is defined as: Java The result of string comparison is: 8