Java Substring Sample Code

The Java String class has a lot of methods to manipulate Strings. The substring() method is a good option to be able to sub divide a string into a new string. The sample code below shows a few different options to substring a String.

Java Substring Source Code

package com.jcd.java.tutorials;

public class JavaSubString
{

	public static void main(String[] args)
	{
		
		String fullString = "this-is-a-very-long-string-for-visual";
		
		//Remove the 'this-' from beginning of string
		String Substring1 = fullString.substring(5);
		System.out.println("\nSubString1="+Substring1);
		
		//Remove the 'this-is-' from beginning of string
		String Substring2 = fullString.substring(8);
		System.out.println("\nSubString2="+Substring2);
		
		//Remove the '-visual' from end of string
		String Substring3 = fullString.substring(0, (fullString.length() -7));
		System.out.println("\nSubString3="+Substring3);
		
		//Remove 'this-is-' from beginning and '-for-visual' from the end of string
		String Substring4 = fullString.substring(8, (fullString.length() -11));
		System.out.println("\nSubString4="+Substring4);

	}

}


Sample Java Substring Output


SubString1=is-a-very-long-string-for-visual

SubString2=a-very-long-string-for-visual

SubString3=this-is-a-very-long-string-for

SubString4=a-very-long-string



Java References:

Add a Comment

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