6

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.

Alex Blasco
  • 793
  • 11
  • 22
Shitab
  • 61
  • 1
  • 1
  • 4

3 Answers3

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