Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a single character appears in a string?

In Java is there a way to check the condition:

"Does this single character appear at all in string x"

without using a loop?

like image 327
barfoon Avatar asked Feb 03 '09 05:02

barfoon


People also ask

How can I check if a single character appears in a string python?

Using in operator The Pythonic, fast way to check for the specific character in a string uses the in operator. It returns True if the character is found in the string and False otherwise. ch = '. '

How do you find a character is present in a string or not?

This str. indexOf() method is used to check the index of the passed character/letter. If the letter/character is present in the string then it will return non-negative value. If the letter/ character is not present in the String, it will return -1.

How do you check if a string contains a specific substring?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.


2 Answers

You can use string.indexOf('a').

If the char a is present in string :

it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.

like image 170
mP. Avatar answered Oct 06 '22 12:10

mP.


  • String.contains() which checks if the string contains a specified sequence of char values
  • String.indexOf() which returns the index within the string of the first occurence of the specified character or substring (there are 4 variations of this method)
like image 37
Zach Scrivena Avatar answered Oct 06 '22 12:10

Zach Scrivena