Java String substring()

Offering a wide range of features and methods, the Java programming language is one of the major programming languages ​​in use today. The list of available data types is one of the most important aspects of any programming language.

Java will classify data types as Primitive and Non-Primitive data types when String is a Non-Primitive type, meaning it refers to an object. Various methods are present in this string object used to perform various string operations. One such method is the substring() function in Java.

Examples:

Extract a substring from text:
let text = "Tech Vidvan!";
let result = text.substring(1, 4);

What is Java String substring():

A portion of a string is returned by the Java String class substring(). We pass beginIndex and endIndex number position in the Java substring method where beginIndex is inclusive, and endIndex is exclusive. For example, the initial index begins at 0 while the end index begins at 1. In the Java String, there are two types of subsparing methods.

Internal implementation substring(int beginIndex):

public String substring(int beginIndex) {    
       if (beginIndex < 0) {    
           throw new StringIndexOutOfBoundsException(beginIndex);    
       }    
       int subLen = value.length - beginIndex;    
       if (subLen < 0) {    
           throw new StringIndexOutOfBoundsException(subLen);    
       }    
       return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);    
   }

Internal implementation substring(int beginIndex, int endIndex):

public String substring(int beginIndex, int endIndex)   
{  
if (beginIndex < 0)   
{  
throw new StringIndexOutOfBoundsException(beginIndex);  
}  
if (endIndex > value.length)   
{  
throw new StringIndexOutOfBoundsException(endIndex);  
}  
int subLen = endIndex - beginIndex;  
if (subLen < 0)   
{  
throw new StringIndexOutOfBoundsException(subLen);  
}  
return ((beginIndex == 0) && (endIndex == value.length)) ? this : new String(value, beginIndex, subLen);  
}

Java String substring() method example:

public class SubstringExample{  
public static void main(String args[]){  
String s1="techvidvan";  
System.out.println(s1.substring(2,4));
System.out.println(s1.substring(2));
}}

Output:
ch
chvidvan

Parameters:

Parameters Description
start Required.

Start position.

First character is at index 0.

end Optional.

End position (up to, but not including).

If omitted: the rest of the string.

Return Value:

Type Description
A string A string containing the extracted characters.

Possible Application:

Substring extraction is used in a wide variety of applications, including prefix and suffix extraction. The name or the denomination alone from a string containing both quantity and currency symbol could be extracted, e.g. to extract Lastname as an example. The latter is explained in more detail below.

The above application shall be implemented in the following way:

public class Techvidvan {
    public static void main(String args[])
    {
        String Str = new String("Rs 1000");
        System.out.print("The original string is : ");
        System.out.println(Str);
        System.out.print("The extracted substring is : ");
        System.out.println(Str.substring(3));
    }
}

Output:
The original string is: Rs 1000
The extracted substring is: 1000

Substring in Java:

Using the provided indices, the substring method in Java can be used to extract a portion of a string and generate a new string.

The substring approach comes in two forms:

  • substring(int StartIndex)
  • substring(int StartIndex, endIndex)

String substring()

A new string that is a substring of the original string is what this method returns. The substring stretches from the character at the startIndex supplied all the way to the string’s conclusion.

Syntax:

public String substring(int StartIndex);

Parameters:

  • StartIndex: the begin index, inclusive.

Return Value:

  • a new string that is a part of the old string is given back. The substring extends to the end of the original string after the character at the startIndex given.

String substring(StartIndex, endIndex):

While the second variant enables you to give both the starting and ending indices for a more precise substring extraction, the first variant extracts the substring from a specified starting index to the end of the string.

Syntax:

public String substring(int StartIndex, int endIndex);

Parameters:

  • startIndex: The substring’s starting index, inclusive.
  • endIndex: The substring’s exclusive ending index.

Return Value:

  • a new string that is a part of the old string is given back. If the second parameter is provided, the substring starts with the character at startIndex and continues up to endIndex – 1.

Examples:

Using substring()

The following example uses substring() to display characters from the string “Techvidvan”:

const anyString = "Techvidvan";
console.log(anyString.substring(0, 1));
console.log(anyString.substring(1, 0)); 
console.log(anyString.substring(0, 6)); 
console.log(anyString.substring(4)); 
console.log(anyString.substring(4, 7)); 
console.log(anyString.substring(7, 4)); 

console.log(anyString.substring(0, 7));
console.log(anyString.substring(0, 10));

Output:
T
T
Techvi
vidvan
vid
vid
Techvid
Techvidvan

Using substring() with length property:

For the extraction of the last characters of a string, the following example uses substring() and length properties. Given you don’t have to know the starting and end indices like in the examples below, this method can be more easily remembered.

const text = "Techvidvan";
console.log(text.substring(text.length - 4)); 
console.log(text.substring(text.length - 5));

Output:
dvan
idvan

Replaces the substring in a string :

A substring of a string is replaced by the following example. It’s replacing both single characters and substrings. The Brave New World string is converted to the Brave New Web by a function call at the end of this example.

function replaceString(oldS, newS, fullS) {
  for (let i = 0; i < fullS.length; ++i) {
    if (fullS.substring(i, i + oldS.length) === oldS) {
      fullS =
        fullS.substring(0, i) +
        newS +
        fullS.substring(i + oldS.length, fullS.length);
    }
  }
  return fullS;
}
replaceString("Hello", "World", "Hi TechVidvan");

Applications of substring() Method:

Replaces the substring in a string A substring of a string is replaced by the following example. It’s replacing both single characters and substrings. The Brave New World string is converted to the Brave New Web by a function call at the end of this example.

Conclusion

A string is a very important data type, and the substring method simply returns part of the original string. Once the subprobation method is called, it creates a new string with an offset and a number. We have given several examples for studying substrings using different methods. Code with relevant screenshots are attached.