Languages
[Edit]
EN

Java - remove substring from string between indexes

0 points
Created by:
Peter-Mortensen
558

In this article, we would like to show you how to create your own function to remove substring from a string in Java.

Practical example

public class StringExample {

    static String removeSubstring(String text, int startIndex, int endIndex) {
        if (endIndex < startIndex) {
            startIndex = endIndex;
        }

        String a = text.substring(0, startIndex);
        String b = text.substring(endIndex);

        return a + b;
    }

    public static void main(String[] args) {
        // Usage example:

        //      index: 0    5 7   11 14
        //             |    | |   |  |
        String text = "This is my text";

        System.out.println( removeSubstring(text, 0, 5));                 // is my text
        System.out.println( removeSubstring(text, 5, 7));                 // This  my text
        System.out.println( removeSubstring(text, 1, text.length() - 1)); // Tt
    }
}

Output:

is my text
This  my text
Tt
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 - remove substring from string between indexes
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.

❤️💻 🙂

Join