When is a character found in a string or not an error

I am trying to use the contains method to determine if a character is in a string or not? I get an error message:

the method contains in the class String cannot be applied to the given types if (str.contains (h)) is required: CharSequence found: char

the code:

str1=rs.getString(1); int len=str1.length(); while(i<len) { char ch=str1.charAt(i); if (str.contains(ch)) continue; else str=str+str1.charAt(i); i++; } 
+4
source share
3 answers

if ( str.indexOf( ch ) != -1 ) should work.

String.contains only accepts CharSequence, but one character is not CharSequence . The method above works for Characters. Another way, as other people have posted (but I want to explain a little more), would be to make your only character in CharSequence, for example by creating String ...

 String x = "" + b; // implicit conversion String y = Character.valueOf(ch).toString(); // explicit conversion 
+3
source

This is because String does not have an overloaded contains() method for char .
Use String.contains () method for CharSequence as -

 String ch = "b"; str.contains(ch); 

Her CharSequence is an interface . A CharSequence is a readable sequence of char values. This interface provides consistent read-only access to various types of char sequences.
All known implementations in the JDK: CharSequence - CharBuffer , Segment , String , StringBuffer , StringBuilder .

+2
source

Below is the declaration for the java.lang.String.contains() method

 public boolean contains(CharSequence s) 

So you must convert the character to a string before passing it to a function

  Character ch = 'c'; str.contains(ch.toString());//converts ch to string and passes to the function 

or

 str.contains(ch+"");//converts ch to string and passes to the function 

Correct code

  str1=rs.getString(1); int len=str1.length(); while(i<len) { char ch=str1.charAt(i); if (str.contains(ch+""))//changed line continue; else str=str+str1.charAt(i); i++; } 
0
source

All Articles