Substring in Java with Examples

In the dynamic landscape of Java programming, mastering the intricacies of string manipulation is essential. A fundamental element within this domain is the concept of substrings—segments of a larger string that hold significant utility.

This article delves into the realm of substrings in Java, exploring methods like substring() and split() to retrieve and manipulate these essential string components. Through practical examples and hands-on exercises, the goal is to provide a comprehensive understanding of substring handling in the Java programming language.

What are substrings?

As the name suggests, substrings are part of a main string, more technically, a substring is a subset of a string. For example, if we have the string “FirstCode”, then “First”, “F”, “Fi”, “Fir”, “Firs”, “Code”, “C”, “Co”, “Cod”, “irst”, “de”, “stCo”, “rstCode”, etc are its substrings.

How do we obtain substrings in Java?

Now that we know what substrings are, we can ask the question: how do we split a string to obtain a substring? Well, thankfully, Java has an inbuilt method called “substring()” that helps us split strings based on the parameters we pass.

The substring() method is a very useful tool for working with strings. It can be used to extract a specific part of a string, to join two strings together, or to create a new string that is a variation of an existing string.

There are 2 ways to use the substring() method, let us take a look at both of them with the help of an example to understand their functionality better. However, before we proceed further, it is very important to note that the indexing of strings starts from 0 and not 1.

1. Specifying only the start index

The substring() method returns a new string that is a portion of the given string. The portion begins at the specified start index (inclusive) and ends at the specified end index (exclusive).

For example, if you have a string “FirstCode” and you call substring(6), you will get the string “ode”. And if you call substring(5), we will get the substring “Code”, as it slices the main string from index 5 to the end (index 8).

If you pass a parameter that is greeted as the length of the string, the compiler will throw an IndexOutOfBoundException as the startIndex is larger than the length of the string. This also happens when the startIndex you passed is less than zero.

Here is an example of a program that uses the substring() method that slices up the string “FirstCode”:

public class Main
{    
    public static void main(String args[])
    {    
        String s="FirstCode";    
        System.out.println("Original String: " + s);  
        System.out.println("Slicing from index 6: " +s.substring(6));  
        System.out.println("Slicing from index 1: " +s.substring(1));  
        System.out.println("Slicing from index 8: " +s.substring(8));
        System.out.println("Slicing from index 5: " +s.substring(5));   
    }  
}

Output:

Slicing from index 6: ode
Slicing from index 1: irstCode
Slicing from index 8: e
Slicing from index 5: Code

2. Specifying both startIndex and endIndex

The substring() method returns a new string that is a part of the given string. The substring starts at the specified start index and ends at the specified end index.

The start index is inclusive, while the end index is exclusive. For example, if you have a string “Hello World” and you call substring(1, 4), you will get the substring “ello”.

Similar to the previous method, an IndexOutOfBoundExceptionis thrown by the compiler when the startIndex is less than zero startIndex is greater than endIndex or endIndex is greater than the length of the String.

Below is an example of the substring method() where it splits the string “FirstCode” depending on the startIndex and endIndex we pass:

public class Main
{    
    public static void main(String args[])
    {    
        String s="FirstCode";    
        System.out.println("Original String: " + s);  
        System.out.println("Substring starting from index 5 to 9: " +s.substring(5,9));    
        System.out.println("Substring starting from index 0 to 5: "+s.substring(0,5));   
        System.out.println("Substring starting from index 5 to 7: "+s.substring(3,7));   
        System.out.println("Substring starting from index 1 to 6: "+s.substring(1,6));   
        System.out.println("Substring starting from index 7 to 9: "+s.substring(7,9));   
    }  
}

Output:

Original String: FirstCode
Substring starting from index 5 to 9: Code
Substring starting from index 0 to 5: First
Substring starting from index 5 to 7: stCo
Substring starting from index 1 to 6: irstC
Substring starting from index 7 to 9: de

Slicing strings using the split() method

The String class’s split() method can be used to extract a substring from a sentence by taking regular expressions as arguments.

Here is an example:

import java.util.*;  
public class Main  
{     
    public static void main(String args[])  
    {    
        String text= new String("FirstCode");   
        String[] sentences = text.split("\\.");  
        System.out.println(Arrays.toString(sentences));  
    }  
}

Output:

[FirstCode]

In the above program, the split() method accepts an argument \\ that checks the sentence and splits the string into another string. This new substring is stored in an array of String objects sentences.

Conclusion

In conclusion, a solid grasp of substring manipulation in Java is a valuable asset for any programmer. The substring() method, with its distinct ways of usage, proves to be a versatile tool for extracting specific portions of strings.

Additionally, the split() method adds another dimension, allowing for the extraction of substrings based on regular expressions. By actively engaging with the provided examples and exercises, readers can enhance their proficiency in handling substrings, thereby bolstering their overall proficiency in Java string manipulation.

Leave a Reply

Your email address will not be published. Required fields are marked *