简体   繁体   中英

How to compare VALUE of two strings?

I'm teaching myself how to code with java and I use exercises I find in the Internet to practice what I learn.

I am now in a middle of a question that asks me to compare between two strings(input from the user) and check if the two contain the same letters.

example:

areAnagrams("asd","dsa") -> true
areAnagrams("Debit Card","Bad Credit")=> true

got the idea?

I know that the == check only if them both are refering to the same object. I thought that

public int compareTo(String otherString)

should have done the job. but it doesnt work =\\

what i did till now is:

public static boolean areAnagrams(String a, String b)
{
int x=0;
    a.trim();
    b.trim();

    x=a.compareTo(b);
    System.out.println(x);
    return x==0 ? true:false;

}
    public static void main(String[] args)
    {
Scanner temp= new Scanner(System.in);
Scanner temp2= new Scanner(System.in);
String a= temp.next();
String b= temp2.next();
System.out.println(areAnagrams(a,b));

    }

}

but it doesnt work. i think there is a command that should compare value's but i couldnt find it online.

will apriciate your help

thanks!

How about trying with Arrays like this:-

 char[] w1= firstWord.trim().toUpperCase().replaceAll("[\\s]", "").toCharArray();
 char[] w2= secondWord.trim().toUpperCase().replaceAll("[\\s]", "").toCharArray();
 Arrays.sort(w1);
 Arrays.sort(w2);
 return Arrays.equals(w1, w2);

The compareTo method checks whether the strings are lexicographically equal, see: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#compareTo(java.lang.String)

You want to compare all the characters in the input Strings.

Anagram algorithm in java

In that link, please see:

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

    // Early termination check, if strings are of unequal lengths,
    // then they cannot be anagrams
    if ( s1.length() != s2.length() ) {
        return false;
    }

    char[] c1 = s1.toCharArray();
    char[] c2 = s2.toCharArray();
    Arrays.sort(c1);
    Arrays.sort(c2);
    String sc1 = new String(c1);
    String sc2 = new String(c2);
    return sc1.equals(sc2);

}`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM