Searching For Characters and Substring in a String in Java
Efficient String manipulation is very important in Java programming especially when working with text-based data. In this article, we will explore essential methods like indexOf(), contains(), and startsWith() to search characters and substrings within strings in Java.
Searching for a Character in a String
1. Using indexOf(char c)
The indexOf()
searchesfor the first occurrence of a character from the beginning of the string and returns its index. If the character is not found, it returns -1
.
Note: If the given string contains multiple occurrences of a specified character then it returns the index of the only first occurrence of the specified character.
Syntax:
int indexOf(char c)
Example:
public class SearchCharacter {
public static void main(String[] args) {
String s = "GeeksforGeeks is a computer science portal";
// Search for the first
// occurrence of 's'
int i = s.indexOf('s');
System.out.println("First occurrence of 's': " + i);
}
}
Output
First occurrence of 's': 4
2. Using lastIndexOf(char c)
The lastIndexOf
() method starts searching backward from the end of the string and returns the index of specified characters whenever it is encountered.
Example:
public class LastOccurrence {
public static void main(String[] args) {
String s = "GeeksforGeeks is a computer science portal";
// Search for the last
// occurrence of 's'
int i = s.lastIndexOf('s');
System.out.println("Last occurrence of 's': " + i);
}
}
Output
Last occurrence of 's': 28
3. Using indexOf(char c, int fromIndex)
It starts searching forward from the specified index in the string and returns the corresponding index when the specified character is encountered otherwise returns -1.
Note: The returned index must be greater than or equal to the specified index.
Syntax:
int indexOf(char c, int fromIndex)
Parameters:
- The character to be searched.
- An integer from where searching.
Return Type: An index of a specified character that appeared at or after the specified index in a forwarding direction.
Example:
public class SearchFromIndex {
public static void main(String[] args) {
String s = "GeeksforGeeks is a computer science portal";
// Search for 's' starting
// from index 10
int i = s.indexOf('s', 10);
System.out.println("Occurrence of 's' after index 10: " + i);
}
}
Output
Occurrence of 's' after index 10: 12
4. Using lastIndexOf(char c, int fromIndex)
It starts searching backward from the specified index in the string. And returns the corresponding index when the specified character is encountered otherwise returns -1.
Note: The returned index must be less than or equal to the specified index.
Syntax:
int lastIndexOf(char c, int fromIndex)
Example:
public class LastSearchFromIndex {
public static void main(String[] args) {
String s = "GeeksforGeeks is a computer science portal";
// Search for 's' starting backward
// from index 20
int i = s.lastIndexOf('s', 20);
System.out.println("Last occurrence of 's' before index 20: " + i);
}
}
Output
Last occurrence of 's' before index 20: 15
5. Using charAt(int index)
The charAt() method returns the character existing at the specified index, indexNumber in the given string. If the specified index number does not exist in the string, the method throws an unchecked exception, StringIndexOutOfBoundsException.
Example:
public class CharAtExample {
public static void main(String[] args) {
String s = "GeeksforGeeks is a computer science portal";
// Get the character at index 10
char ch = s.charAt(10);
System.out.println("Character at index 10: " + ch);
}
}
Output
Character at index 10: e
Searching for a Substring in a String
1. Using indexOf(String substring)
Finds the first occurrence of a substring.
Example:
public class SearchSubstring {
public static void main(String[] args) {
String s = "GeeksforGeeks is a computer science portal";
// Search for "Geeks"
int i = s.indexOf("Geeks");
System.out.println("First occurrence of 'Geeks': " + i);
}
}
Output
First occurrence of 'Geeks': 0
2. Using contains(CharSequence seq)
It returns true if the string contains the specified sequence of char values otherwise returns false. Its parameters specify the sequence of characters to be searched and throw NullPointerException if seq is null.
Syntax:
boolean contains(CharSequence seq)
Note: CharSequence is an interface that is implemented by String class, Therefore we use string as an argument in contains() method.
Example:
public class ContainsExample {
public static void main(String[] args) {
String s = "GeeksforGeeks";
System.out.println("Contains 'Geeks': " + s.contains("Geeks"));
System.out.println("Contains 'for': " + s.contains("for"));
System.out.println("Contains 'eeks': " + s.contains("eeks"));
}
}
Output
Contains 'Geeks': true Contains 'for': true Contains 'eeks': true
Checking String Start or End
- boolean startsWith(String str): Returns true if the string str exists at the starting of the given string, else false.
- boolean startsWith(String str, int indexNum): Returns true if the string str exists at the starting of the index indexNum in the given string, else false.
- boolean endsWith(String str): Returns true if the string str exists at the ending of the given string, else false.
Example:
// Java Program to Match ofstart and endof a Substring
import java.io.*;
class GFG {
public static void main(String[] args) {
// Input string in which substring
// is to be searched
String s = "GeeksforGeeks is a computer science portal";
// Print and display commands
System.out.println(s.startsWith("Geek"));
System.out.println(s.startsWith("is", 14));
System.out.println(s.endsWith("port"));
}
}
Output
true true false
Summary of all Methods
- indexOf(char c): It finds the first occurrence of a character.
- lastIndexOf(char c): It finds the last occurrence of a character.
- indexOf(String s): It finds the first occurrence of a substring.
- contains(CharSequence seq): It checks if the string contains the specified sequence.
- startsWith(String prefix): It checks if the string starts with the specified prefix.
- endsWith(String suffix): It checks if the string ends with the specified suffix.