[英]What's the most concise way in Java to get the “Alpha” out of “AlphaSuffix”?
If I have a string such as one of the following: 如果我有一个字符串,如下列之一:
AlphaSuffix
BravoSuffix
CharlieSuffix
DeltaSuffix
What is the most concise Java syntax to transform AlphaSuffix
into Alpha
into BravoSuffix
into Bravo
? 将
AlphaSuffix
转换为Alpha
并将BravoSuffix
转换为Bravo
的最简洁的Java语法是什么?
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
. 在实用程序方法中,我添加了一个检查以查看后缀是否实际位于
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
Use a simple regexp to delete the suffix: 使用简单的正则表达式删除后缀:
String myString = "AlphaSuffix";
String newString = myString.replaceFirst("Suffix$", "");
如果后缀都是不同的/未知的,你可以使用
myString.replaceFirst("^(Alpha|Bravo|Charlie|Delta|...).*", "$1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.