Java 兩字串比對

要檢驗兩個字串,內容是否相同,不論排序

ie listen silten 就是相同的

我寫了個程式 但是sort的部分一直錯

有人可以幫我看一下嗎 ??

import java.util.Scanner;

import java.util.Arrays;

public class checks {

public static void main(String[] args) {

System.out.print("Please input the first String: ");

Scanner input = new Scanner(System.in);

String s1= input.nextLine();

System.out.print("Please input the second String: ");

String s2= input.nextLine();

System.out.println(isAnagram(s1,s2));

}

public static boolean isAnagram(String s1, String s2) {

int[] s3=new int[s1.length()];

int[] s4=new int[s2.length()];

for(int i=0;i<s1.length();i++){

s3[i]= s1.charAt(i);

}

for(int i=0;i<s2.length();i++){

s4[i]= s2.charAt(i);

}

int s5[] = java.util.Arrays.sort(s3); // 這邊一直錯

int s6[] = java.util.Arrays.sort(s4); // 這邊一直錯

if (s1.length() != s2.length()) // 先比較兩個 字串長度是否相同

return false;

for(int i=0;i< s1.length(); i++) { // 再逐一比較字母內容是否一致

if (s5[i] != s6[i] )

return false;

}

}

1 Answer

Rating
  • John
    Lv 7
    7 years ago
    Favorite Answer

    唔可以咁用,因為Arrays.sort(),唔會點傳任何嘢。用compareTo就可以達到妳要的效果。

    import java.util.*;

    public class Program {

    public static void main(String[] args) {

    String first = read("Please input the first string: ");

    String second = read("Please input the second string: ");

    int result = compare(first, second);

    if (result == 0) {

    System.out.println("same");

    } else {

    System.out.println("not same");

    }

    System.exit(0);

    }

    private static String read(String message) {

    System.out.print(message);

    Scanner keyboard = new Scanner(System.in);

    return keyboard.nextLine();

    }

    private static int compare(String first, String second) {

    return reformat(first).compareTo(reformat(second));

    }

    private static String reformat(String value) {

    char[] chars = value.toCharArray();

    Arrays.sort(chars);

    return String.valueOf(chars).trim();

    }

    }

Still have questions? Get your answers by asking now.