Languages
[Edit]
EN

Java - remove substring from string between indexes

0 points
Created by:
Dirask Admin - Marvin
1820

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

Java - String (popular problems)

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