Home > Tutorial > Java Substring Sample Code

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:

Seymour
Posted by

Seymour

I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot