I want to take a char using charAt() from a string and want to search in another string using contains(). charAt() gives me a char and when I use contains() I need a CharSequence parameter to search that character in the second string.
Asked
Active
Viewed 3.4k times
6
-
2What does this have to do with C#? – DavidG May 09 '19 at 09:32
-
3`Character.toString(yourChar)`. – Sweeper May 09 '19 at 09:34
-
In Java you would use [indexOf()](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#indexOf-int-) where you can pass a character directly. – vanje May 09 '19 at 09:40
3 Answers
6
A CharSequence is basically a string, you can concatenate an empty string with a char this will give you a string containing 1 char only. You can also do String.valueOf(char here) or Character.toString(char here)
String a = "abc";
String b = "anthony";
char c = a.charAt(0);
b.contains("" + c);
b.contains(String.valueOf(c));

anthony yaghi
- 532
- 2
- 10
4
I give you an example:
Syntax of String contains
method
public boolean String.contains(CharSequence s)
Parameters
String "e" − This is the sequence to search
Return Value
This method returns true only if this string contains "e" else false.
Exception
NullPointerException − if the value of the parameter is null.
Example
String yourSentence = "Hello world";
char yourChar = yourSentence.charAt(1);
String anotherSentence "Hello everyone";
boolean result = anotherSentence.contains(String.valueOf(yourChar)));

Matthias
- 7,432
- 6
- 55
- 88

Alex Blasco
- 793
- 11
- 22
0
as a one line :
stringToSearch.contains(Character.toString(aString.charAt(5)));

nullPointer
- 4,419
- 1
- 15
- 27