Site icon Bytefreaks.net

Java: remove leading character (or any prefix) from String only if it matches

Advertisements

The following snippet allows you to check if a String in Java starts with a specific character (or a specific prefix) that you are looking for and remove it.
To keep the number of lines small, we used the Java ?: ternary operator, which defines a conditional expression in a compact way.
Then, to quickly check if the first character(s) is the one we are looking for before removing it we used the String.startsWith().
To compute the number of characters to remove we used the String.length() on the needle.
Finally, to strip the leading character(s) we used String.substring() whenever the prefix matched.


final String needle = "//";
final int needleSize = needle.length();
String haystack = "";
haystack = haystack.startsWith(needle) ? haystack.substring(needleSize) : haystack;
System.out.print(haystack);

haystack = "apple";
haystack = haystack.startsWith(needle) ? haystack.substring(needleSize) : haystack;
System.out.println(haystack);

haystack = "//banana";
haystack = haystack.startsWith(needle) ? haystack.substring(needleSize) : haystack;
System.out.println(haystack);

The above code will result in the following:


apple
banana

 

Bonus: to remove all the instances of a character anywhere in a string:


final String needle = "a";
final int needleSize = needle.length();
String haystack = "banana";
haystack = haystack.replace(needle,"");
System.out.println(haystack);

The above code will result in the following:

bnn

Bonus: to remove the first instance of a character anywhere in a string:


final String needle = "a";
final int needleSize = needle.length();
String haystack = "banana";
haystack = haystack.replaceFirst(needle,"");
System.out.println(haystack);

The above code will result in the following:

bnana

This post is also available in: Αγγλικα

Exit mobile version