- 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
Java Program to locate a character in a string
To locate a character in a string, use the indexOf() method.
Let’s say the following is our string.
String str = "testdemo";
Find a character ‘d’ in a string and get the index.
int index = str.indexOf( 'd');
Example
public class Demo { public static void main(String []args) { String str = "testdemo"; System.out.println("String: "+str); int index = str.indexOf( 'd' ); System.out.printf("'d' is at index %d
", index); } }
Output
String: testdemo 'd' is at index 4
Let us see another example. The method returns -1, if the character isn’t found −
Example
public class Demo { public static void main(String []args) { String str = "testdemo"; System.out.println("String: "+str); int index = str.indexOf( 'h' ); System.out.printf("'h' is at index %d
", index); } }
Output
String: testdemo 'h' is at index -1
- Related Articles
- Java Program to locate a substring in a string
- Java Program to access character of a string
- Java program to convert a character array to string
- Java Program to Find the Frequency of Character in a String
- Java Program to Get a Character From the Given String
- Java program to find the Frequency of a character in a given String
- Java Program to replace all occurrences of a given character in a string
- Java Program to Convert Character to String
- Java program to check if a string contains any special character
- Java Program to Replace the Spaces of a String with a Specific Character
- Java Program to Capitalize the first character of each word in a String
- Java program for removing n-th character from a string
- Java program to count the occurrence of each character in a string using Hashmap
- Java program to check occurence of each character in String
- Java program to check occurrence of each character in String

Advertisements