Java Data Type Tutorial - Java Sub Strings








Getting a Substring

We can use the substring() method to get a sub-part of a string.

We can takes the start index as the parameter and returns a substring beginning at the start index to the end of string.

We can also takes the start index and the end index as parameters.

It returns the substring beginning at the start index and one less than the end index.

For example,

String s1  = "Hello".substring(1); // s1  has  "ello" 
String s2  = "Hello".substring(1, 4); // s2  has  "ell"

Splitting Strings

Use the split() method to split a string into multiple strings.

Splitting is performed using a delimiter.

The split() method returns an array of String.

public class Main {
  public static void main(String[] args) {
    String str = "A,B,C,D";
/*from   w w w . j a  va  2  s.  c  o  m*/
    // Split str using a comma as the delimiter
    String[] parts = str.split(",");

    // Print the the string and its parts
    System.out.println(str);

    for (String part : parts) {
      System.out.println(part);
    }
  }
}

The code above generates the following result.





Join Strings

static join() method joins multiple strings into one string. It is overloaded.

String  join(CharSequence delimiter, CharSequence... elements)
String  join(CharSequence delimiter,  Iterable<? extends CharSequence>  elements)

The first version takes a delimiter and a sequence of strings to be joined.

The second version takes a delimiter and an Iterable, for example, a List or Set.

The following code uses the first version to join some strings:

String str = String.join(",", "A",  "F", "N", "C", "A"); 
System.out.println(str);