Java - get substring from string

0 points
Created by:

In this article, we would like to show you how to get a substring of the string in Java.

Quick solution:

String text = "abcd";
String substring = text.substring(0, 2);   // start from index 0 up to 2
System.out.println(substring);             // ab


Practical example

In this example, we present different cases of how to get a substring from the text.

public class Example {
    public static void main(String[] args) {
        String text = "abcd";

        String substring1 = text.substring(0, 2);  // start from index 0 to 2
        String substring2 = text.substring(1, 3);  // start from index 1 to 3
        String substring3 = text.substring(0);     // from index 0 to the end of the string

        System.out.println(substring1);  // ab
        System.out.println(substring2);  // bc
        System.out.println(substring3);  // abcd
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - String (popular problems)

Java - get substring of string
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂