Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Taking Strings Apart with Substrings

Problem

You want to break a string apart into substrings by position.

Solution

Use the String object’s substring( ) method.

Discussion

The substring( ) method constructs a new String object made up from a run of characters contained somewhere in the original string, the one whose substring( ) you called. The name of this method, substring(), violates the stylistic dictum that words should be capitalized; if Java were 100.0% consistent, this would be named subString. But it’s not; it’s substring. The substring method is overloaded: both forms require a starting index. The one-argument form returns from startIndex to the end. The two-argument form takes an ending index (not a length, as in some languages), so that an index can be generated by the String methods indexOf( ) or lastIndexOf( ). Note that the end index is one beyond the last character!

// File SubStringDemo.java
public static void main(String[] av) {
    String a = "Java is great.";
    System.out.println(a);
    String b = a.substring(5);    // b is the String "is great."
    System.out.println(b);
    String c = a.substring(5,7);// c is the String "is"
    System.out.println(c);
    String d = a.substring(5,a.length(  ));// d is "is great."
    System.out.println(d);
}

This prints the following when run:

> java SubStringDemo
Java is great.
is great.
is
is great.
>
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata