Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (6.5k points)
edited by
Could someone tell me what is the shortest method to check if a character exists in a String or not?

1 Answer

0 votes
by (11.3k points)
edited by
The shortest way to check for the availability of a character in a String without having to manually iterate through it is done via a pre-built function inside JAVA known as indexOf().

If we have to check for the availability of a character 'a' inside a String y="bac", we use:

int v=y.indexOf('a');

The function returns the index of the character in the String on its availability and returns '-1' otherwise. Here, the value of v will be  '1' since the character 'a' is on index number 1.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 9, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Oct 29, 2019 in Java by Anvi (10.2k points)

Browse Categories

...