- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find a unique character in a string using java?
You can find whether the given String contains specified character in the following ways −
Using the indexOf() method
You can search for a particular letter in a string using the indexOf() method of the String class. This method returns an integer parameter which is a position index of a word within the string or, -1 if the given character does not exist in the specified String.
Therefore, to find whether a particular character exists in a String −
Invoke the indexOf() method on the String by passing the specified character as a parameter.
If the return value of this method is not -1 then the String it indicates that contains the specified character.
Example
import java.util.Scanner; public class IndexOfExample { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the required String: "); String str = sc.next(); System.out.println("Enter the required character: "); char ch = sc.next().toCharArray()[0]; //Invoking the index of method int i = str.indexOf(ch); if(i!=-1) { System.out.println("Sting contains the specified character"); } else { System.out.println("String doesn’t contain the specified character"); } } }
Output
Enter the required String: Tutorialspoint Enter the required character: t Sting contains the specified character
Using the toCharArray() method
The toCharArray() method of the String class converts the given String into an array of characters and returns it.
Therefore, to find whether a particular character exists in a String −
Convert it into an array of characters.
Compare each character in the array with the required one.
In case of a /match the String contains the required character.
Example
import java.util.Scanner; public class FindingCharacter { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the required String: "); String str = sc.next(); System.out.println("Enter the required character: "); char ch = sc.next().toCharArray()[0]; //Converting the String to char array char charArray[] = str.toCharArray(); boolean flag = false; for(int i = 0; i < charArray.length; i++) { flag = true; } if(flag) { System.out.println("Sting contains the specified character"); } else { System.out.println("String doesnt conatin the specified character"); } } }
Output
Enter the required String: tutorialspoint Enter the required character: T Sting contains the specified character