开发者

What's the most concise way in Java to get the "Alpha" out of "AlphaSuffix"?

开发者 https://www.devze.com 2023-03-30 12:13 出处:网络
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 Bravo

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");
0

精彩评论

暂无评论...
验证码 换一张
取 消