If I have a string such as one of the following:
AlphaSuffix
BravoSuffix
CharlieSuffix
DeltaSuffix
What is the most concis开发者_如何学Goe Java syntax to transform AlphaSuffix
into Alpha
into BravoSuffix
into Bravo
?
Use a simple regexp to delete the suffix:
String myString = "AlphaSuffix";
String newString = myString.replaceFirst("Suffix$", "");
Chop it off.
String given = "AlphaSuffix"
String result = given.substring(0, given.length()-"Suffix".length());
To make it even more concise, create a utility method.
public static String chop(String value, String suffix){
if(value.endsWith(suffix)){
return value.substring(0, value.length() - suffix.length());
}
return value;
}
In the utility method, I've added a check to see if the suffix is actually at the end of the value
.
Test:
String[] sufs = new String[] {
"AlphaSuffix",
"BravoSuffix",
"CharlieSuffix",
"DeltaSuffix"
};
for (int i = 0; i < sufs.length; i++) {
String s = chop(sufs[i], "Suffix");
System.out.println(s);
}
Gives:
Alpha
Bravo
Charlie
Delta
if suffixes are all different/unkown you can use
myString.replaceFirst("^(Alpha|Bravo|Charlie|Delta|...).*", "$1");
精彩评论