Substring in java

 
Substring in java

In Java, a substring refers to a portion of a string. It allows you to extract a part of a string based on its starting index and optionally its ending index. The syntax for extracting a substring in Java is:

javaCopy code
String substring(int beginIndex) String substring(int beginIndex, int endIndex)

The substring(int beginIndex) method returns a new string that is a substring of the original string starting from the beginIndex inclusive to the end of the string.

The substring(int beginIndex, int endIndex) method returns a new string that is a substring of the original string starting from the beginIndex inclusive and ending just before the endIndex.


Code Example :


public class substr {
    public static void main(String[] args) {
        String name = "Asgar";
        for (int i = 0; i <= name.length(); i++) {
            System.out.println(name.substring(0, i));
        }
     
    }
}

Output:

A As Asg Asga Asgar


another Code Example:



public class SubstringExample {
    public static void main(String[] args) {
        String str = "Hello, World!";
       
        // Extract substring from index 7 to the end
        String substr1 = str.substring(7);
        System.out.println(substr1); // Output: World!
       
        // Extract substring from index 7 to index 12 (exclusive)
        String substr2 = str.substring(7, 12);
        System.out.println(substr2); // Output: World
    }
}

Read more

No comments: