How to check if char is NOT in a string? (java, junit)

As the name says, I am having problems passing junit tests to check if there is a character in a string and how to check if an empty string contains a character. here is my method:

     public static boolean isThere(String s, char value){
  for(int x = 0; x <= s.length(); x++){
   if(s.charAt(x) == value){
    return true;
   } else if(s.length() == 0){
    return false;
   }
  }
  return false;

And here is the junit test:

    public void testIsThere() {
  {
   String sVal  = "Jeff George";
   boolean hasA = StringMethods.isThere(sVal,'e');
   assertTrue(hasA);
   boolean hasE = StringMethods.isThere(sVal, 'o');
   assertTrue(hasE);
   boolean notIn = StringMethods.isThere(sVal,'b');
   assertTrue(notIn);
  }
  {
   String sVal  = "";
   boolean nothingIn = StringMethods.isThere(sVal,'a');
   assertFalse(nothingIn);
   boolean notIn = StringMethods.isThere(sVal,'b');
   assertFalse(notIn); 
  }
 }

Thanks, appreciated

+3
source share
6 answers

Use instead String.indexOf():

public static boolean contains(String s, char value){
    return s != null && s.indexOf(value) > -1;
}

String sVal = "Jeff George";
assertTrue(contains(sVal, 'e'));
sVal = null;
assertFalse(contains(sVal, 'e'));
+14
source

Why are you doing this? Your function is already implemented as a method in String. Use String.indexOf instead :

s.indexOf('a') == -1

, - assertFalse not assertTrue :

String sVal  = "Jeff George";
boolean notIn = StringMethods.isThere(sVal, 'b');
assertFalse(notIn); // not assertTrue

, notIn - - , . , .

+4

Java 6

final String s = "This is a test";
s.contains("x"); // False
s.contains("t"); // True
+2

?

-,

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

. x (use x < s.length() , ). , (. ).

+1

String.indexOf(char) -1, hasA . .

0

Source: https://habr.com/ru/post/1738408/


All Articles