-3

How do you write a code that Returns true if s(a string) contains none of the characters found in chars(another string) or false otherwise?

char[] original = s.toCharArray(); 


char [] sub = chars.toCharArray();

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

{

if (s.contains(chars)

{

return true;

}

}

return false;
aby12
  • 5
  • 3
  • 3
    Nevermind how I write it, how will you write it since it's your homework? – Kayaman Oct 07 '19 at 06:40
  • If you're thrown by the logic as presented, try inverting it... first write a code that returns `true` if a string *does* contain some characters from another string. And then return the negation of that function. – Elliott Frisch Oct 07 '19 at 06:41
  • This is fairly straight forward. Have you looked at the [String](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html) reference? Please post what you have tried. – Ambro-r Oct 07 '19 at 06:41
  • 1
    Possible duplicate of [How do I check if a string contains a list of characters?](https://stackoverflow.com/questions/14392270/how-do-i-check-if-a-string-contains-a-list-of-characters) – Petter Friberg Oct 07 '19 at 06:41
  • Negate the suggested dupe – Petter Friberg Oct 07 '19 at 06:42
  • char[] original = s.toCharArray(); char [] sub = chars.toCharArray(); for(int i = 0; i – aby12 Oct 07 '19 at 06:43
  • you want us to explain the 'contains' method? – Stultuske Oct 07 '19 at 06:53
  • yeah pls when I try to say s.contains(char) { return true}.....this isn't working .thats why im confused – aby12 Oct 07 '19 at 07:12
  • @aby12 that code also makes little sense. How exactly did you implement it? Don't explain it in a comment, edit your question and add the information there – Stultuske Oct 07 '19 at 07:19

1 Answers1

0

Try below code, the results are false, true.

public class Main {
    public static void main(String[] args) {
        System.out.println(isNotContained("abc", "dc"));
        System.out.println(isNotContained("abc", "de"));
    }

    private static boolean isNotContained(final String source, final String target) {
        char[] original = source.toCharArray();
        for (char c : original) {
            if (target.contains(String.valueOf(c))) {
                return false;
            }
        }
        return true;
    }
}
Qilin Lou
  • 396
  • 3
  • 15