Keith Axelrod
Keith Axelrod

Reputation: 175

How do I check if one string contains characters from another string?

I want to create a boolean method that allows me to check if the characters in one string randomly generated in a method before contains characters from a string that the user inputs.

Example:

Random base word: Cellphone

User word: Cell --> Yes this is okay.

User word: Cells --> No, it contains letters not found in original word given.

I'm thinking we can maybe do something that looks like this:

public static class boolean usesSymbolsFromWord(String candidate, String base) {
  //pseudocode

  characters in String candidate are found in String base
  return true;
  }
return false;
}

Upvotes: 3

Views: 5061

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136102

try this func

boolean allS1CharsAreInS2(String s1, String s2) {
    for(int i = 0; i < s1.length(); i++) {
        char c = s1.charAt(i);
        if (s2.indexOf(c) == -1) {
            return false;
        }
    }
    return true;
}

Upvotes: 1

Kartic
Kartic

Reputation: 2985

I normally use : word1.toUpperCase().contains(word2.toUpperCase()) as I prefer case insensitive check. But its based on your requirement. If it has to be case sensitive checking, you can use word1.contains(word2)

Upvotes: 0

Obl Tobl
Obl Tobl

Reputation: 5684

Just try it with a build in method of Java.lang.String:

base.contains(candidate);

That's all.

For further informations see the Java Docs:

contains(CharSequence s)
Returns true if and only if this string contains the specified sequence of char values.

Upvotes: 1

Related Questions