Open In App

Searching For Characters and Substring in a String in Java

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Strings are a very important aspect from a programming perspective as many questions can be framed out among strings. There arise wide varied sets of concepts and questions that are pivotal to understanding strings. Now over here will be discussing different ways to play with strings where we will be playing with characters with strings and substrings which is a part of input strings with help of inbuilt methods and also by proposing logic listing wide varied ways as follows: 

Searching a Character in the String

Way 1: indexOf(char c)

It searches the index of specified characters within a given string. It starts searching from the beginning to the end of the string (from left to right) and returns the corresponding index if found otherwise 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)
// Accepts character as argument, Returns index of 
// the first occurrence of specified character 

Way 2: lastIndexOf(char c)

It starts searching backward from the end of the string and returns the index of specified characters whenever it is encountered. 

Syntax: 

public int lastIndexOf(char c)
// Accepts character as argument, Returns an 
// index of the last occurrence specified 
// character

Way 3: indexOf(char c, int indexFrom)

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: 

public int IndexOf(char c, int indexFrom)

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.

Way 4: 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: 

public int lastIndexOf(char c, int fromIndex)

Way 5: charAt(int indexNumber)

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. 

Syntax:

char charAt(int indexNumber)

Example:

 

Java




// Java Program to Illustrate to Find a Character
// in the String
  
// Importing required classes
import java.io.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // String in which a character to be searched.
        String str
            = "GeeksforGeeks is a computer science portal";
  
        // Returns index of first occurrence of character.
        int firstIndex = str.indexOf('s');
        System.out.println("First occurrence of char 's'"
                           + " is found at : "
                           + firstIndex);
  
        // Returns index of last occurrence specified
        // character.
        int lastIndex = str.lastIndexOf('s');
        System.out.println("Last occurrence of char 's' is"
                           + " found at : " + lastIndex);
  
        // Index of the first occurrence of specified char
        // after the specified index if found.
        int first_in = str.indexOf('s', 10);
        System.out.println("First occurrence of char 's'"
                           + " after index 10 : "
                           + first_in);
  
        int last_in = str.lastIndexOf('s', 20);
        System.out.println("Last occurrence of char 's'"
                           + " after index 20 is : "
                           + last_in);
  
        // gives ASCII value of character at location 20
        int char_at = str.charAt(20);
        System.out.println("Character at location 20: "
                           + char_at);
  
        // Note: If we uncomment it will throw
        // StringIndexOutOfBoundsException
        // char_at = str.charAt(50);
    }
}


Output

First occurrence of char 's' is found at : 4
Last occurrence of char 's' is found at : 28
First occurrence of char 's' after index 10 : 12
Last occurrence of char 's' after index 20 is : 15
Character at location 20: 111

 Way 6: Searching Substring in the String

The methods used for searching a character in the string which are mentioned above can also be used for searching the substring in the string. 

Example

Java




// Java Program to illustrate to Find a Substring
// in the String
  
// Importing required classes
import java.io.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
  
        // A string in which a substring
        // is to be searched
        String str
            = "GeeksforGeeks is a computer science portal";
  
        // Returns index of first occurrence of substring
        int firstIndex = str.indexOf("Geeks");
  
        System.out.println("First occurrence of char Geeks"
                           + " is found at : "
                           + firstIndex);
  
        // Returns index of last occurrence
        int lastIndex = str.lastIndexOf("Geeks");
        System.out.println(
            "Last occurrence of char Geeks is"
            + " found at : " + lastIndex);
  
        // Index of the first occurrence
        // after the specified index if found
        int first_in = str.indexOf("Geeks", 10);
        System.out.println("First occurrence of char Geeks"
                           + " after index 10 : "
                           + first_in);
  
        int last_in = str.lastIndexOf("Geeks", 20);
        System.out.println("Last occurrence of char Geeks "
                           + "after index 20 is : "
                           + last_in);
    }
}


Output

First occurrence of char Geeks is found at : 0
Last occurrence of char Geeks is found at : 8
First occurrence of char Geeks after index 10 : -1
Last occurrence of char Geeks after index 20 is : 8

Way 7: 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: 

public 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 

Java




// Java Program to Illustrate How to Find a Substring
// in the String using contains() Method
  
// Importing required classes
import java.io.*;
import java.lang.*;
  
// Class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // String in which substring
        // to be searched
        String test = "software";
  
        CharSequence seq = "soft";
        boolean bool = test.contains(seq);
        System.out.println("Found soft?: " + bool);
  
        // Returns true substring if found.
        boolean seqFound = test.contains("war");
        System.out.println("Found war? " + seqFound);
  
        // Returns true substring if found
        // otherwise return false
        boolean sqFound = test.contains("wr");
        System.out.println("Found wr?: " + sqFound);
    }
}


Output

Found soft?: true
Found war? true
Found wr?: false

 Way 8: Matching String Start and 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




// Java Program to Match ofstart and endof a Substring
  
// Importing required classes
import java.io.*;
  
// Main class
class GFG {
  
    // Main driver method
    public static void main(String[] args)
    {
        // Input string in which substring
        // is to be searched
        String str
            = "GeeksforGeeks is a computer science portal";
  
        // Print and display commands
        System.out.println(str.startsWith("Geek"));
        System.out.println(str.startsWith("is", 14));
        System.out.println(str.endsWith("port"));
    }
}


Output

true
true
false



Previous Article
Next Article

Similar Reads

Modify string by inserting characters such that every K-length substring consists of unique characters only
Given string S of size N consisting of K distinct characters and (N - K) '?'s, the task is to replace all '?' with existing characters from the string such that every substring of size K has consisted of unique characters only. If it is not possible to do so, then print "-1". Examples: Input: S = "????abcd", K = 4Output: abcdabcdExplanation:Replaci
6 min read
Longest Substring of given characters by replacing at most K characters for Q queries
Given a string s of length N, and Q queries, each of type (K, C) where K is an integer C is a character, the task is to replace at most K characters of the string by C and have to print the maximum length of possible substring containing only character C. Examples : Input: s = "yamatonadeshiko", N = 15, Q = 10, queries[] = {{1, a}, {2, a}, {3, a},
12 min read
Longest substring with atmost K characters from the given set of characters
Given a string S, an integer K and set of characters Q[], the task is to find the longest substring in string S which contains atmost K characters from the given character set Q[].Examples: Input: S = "normal", Q = {"a", "o", "n", "m", "r", "l"}, K = 1 Output: 1Explanation: All the characters in the given string S are present in array. Therefore, w
9 min read
Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'th substring
Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'nd substring. Examples: Input : "11235813" Output : ["1", "1", "2", "3", "5", "8", "13"] Input : "1111223" Output : ["1", "11", "12", "23"] Input : "1111213" Output : ["11", "1", "12", "13"] Input : "11121114" Output : []Iterate through the given string by pickin
9 min read
Extract a Substring Between Two Characters in a String in Java
In Java, the extraction of the substring between the two characters in a string can be implemented with the substring method, and string is a pre-defined method in the class of the String. A String is a pre-defined class of the java.lang package. substring(startIndex, endIndex): This is a pre-defined method of the String class, and it takes the two
2 min read
Check if a string can be split into two substrings such that one substring is a substring of the other
Given a string S of length N, the task is to check if a string can be split into two substrings, say A and B such that B is a substring of A. If not possible, print No. Otherwise, print Yes. Examples : Input: S = "abcdab"Output: YesExplanation: Considering the two splits to be A="abcd" and B="ab", B is a substring of A. Input: S = "abcd"Output: No
5 min read
Count occurrences of substring X before every occurrence of substring Y in a given string
Given three strings S, X, and Y consisting of N, A, and B characters respectively, the task is to find the number of occurrences of the substring X before every occurrence of the substring Y in the given string S. Examples: Input S = ”abcdefdefabc”, X = ”def”, Y = ”abc”Output: 0 2Explanation:First occurrence of Y(= "abc"): No of occurrences of X(=
6 min read
Longest substring whose any non-empty substring not prefix or suffix of given String
Given a string S of length N, the task is to find the length of the longest substring X of the string S such that: No non-empty substring of X is a prefix of S.No non-empty substring of X is a suffix of S.If no such string is possible, print −1. Examples: Input: S = "abcdefb"Output: 4Explanation: cdef is the substring satisfying the conditions. Inp
5 min read
Minimum removals to make a string concatenation of a substring of 0s followed by a substring of 1s
Given binary string str of length N​​​​, the task is to find the minimum number of characters required to be deleted from the given binary string to make a substring of 0s followed by a substring of 1s. Examples: Input: str = "00101101"Output: 2Explanation: Removing str[2] and str[6] or removing str[3] and str[6] modifies the given binary string to
11 min read
Find if a given string can be represented from a substring by iterating the substring “n” times
Given a string 'str', check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. Examples: Input: str = "abcabcabc" Output: true The given string is 3 times repetition of "abc" Input: str = "abadabad" Output: true The given string is 2 times repetition of "abad" Input: str = "aabaabaabaab" Ou
20 min read