Sesha
Sesha

Reputation: 3

compare to strings having same characters or alphabets

I am new to Java programming and recently started working on string operations.
Can anyone suggest me a working idea to check whether to string consists of same character sets?

Example:

string1="add" so string1 has characters "a,d"
string2="dad" so string2 has characters "a,d"
--> they match

String1="abc"
string2="abcd"
--> they don't match

I don't want letter by letter comparison

Upvotes: 1

Views: 227

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500495

It sounds like you're trying to check whether the set of characters contained within one string is the same as the set of characters contained within another. That's reasonably easy to achieve with a Set<Character>:

static boolean characterSetsEqual(String text1, String text2) {
    Set<Character> set1 = toCharacterSet(text1);
    Set<Character> set2 = toCharacterSet(text2);
    return set1.equals(set2);
}

static Set<Character> toCharacterSet(String input) {
    Set<Character> set = new HashSet<>();
    for (int i = 0; i < input.length(); i++) {
        set.add(input.charAt(i));
    }
    return set;
}

Set<>.equals is defined in exactly the way that you want it to be:

Compares the specified object with this set for equality. Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.

It's important to see that you really are interested in sets here - the conversion from a String (which is a sequence of characters) into a Set<Character> (which has no inherent order, nor a count of how many times each character appears) is the crucial part.

Upvotes: 4

RMachnik
RMachnik

Reputation: 3684

This is simple library that might help you with bassic operations on strings for the begening and also please look at String class documentation there are also many usefull stuff.

Upvotes: 0

Related Questions