Languages
[Edit]
EN

Java - remove prefix from string

0 points
Created by:
Wallace
636

In this article, we would like to show you how to remove prefix from string in Java.

Quick solution:

String text = "ABCD";

// replace "AB" only if it is at the beginning
String result1 = text.replaceAll("^AB","");

// remove the first two characters
String result2 = text.substring(2);


System.out.println(result1);  // CD
System.out.println(result2);  // CD

 

Practical examples

1. String replaceAll() with regex

In this example, we use replaceAll() method with regex to replace the first two letters (AB) with an empty string.

public class Example {

    public static void main(String[] args) {
        String text = "ABCD";

        // replace the AB only at the beginning of the string
        String result = text.replaceAll("^AB", "");

        System.out.println(result);  // CD
    }
}

2. String substring()

In this example, we use substring() method to remove first two letters from the text.

public class Example {

    public static void main(String[] args) {
        String text = "ABCD";

        // remove the first two characters
        String result = text.substring(2);

        System.out.println(result);  // CD
    }
}
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 prefix from 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.

❤️💻 🙂

Join