简体   繁体   English

Java中最简洁的方法是从“AlphaSuffix”中获取“Alpha”?

[英]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.

相关问题 编写此 java 代码的最简洁/最佳方式是什么? - What's the most concise / best way to write this java code? 从地图中获得最高n个数字的最简洁方法? - Most concise way to get highest n numbers out of a map? 在 Java 中比较版本的最简洁方法 - Most concise way of comparing versions in Java 使用Java 8,打印文件中所有行的最优选和简洁方法是什么? - Using Java 8, what is the most preferred and concise way of printing all the lines in a file? 使用Java 8,创建排序和分组字符串列表的最简洁方法是什么 - Using Java 8, what is the most concise way of creating a sorted AND grouped list of Strings 使用Java 8,迭代地图中所有条目的最简洁方法是什么? - Using Java 8, what is the most concise way of iterating through all the entries in a map? 用反序列化编写Java类以表示简单的JSON文档的最简洁方法是什么? - What is the most concise way to write a Java class to represent a simple JSON document, with deserialization? 在Java中测试函数输出的简洁方法是什么? - What is a concise way to test outputs of a function in java? 从Java Date对象中删除时间的最有效方法是什么? - What's the most efficient way to strip out the time from a Java Date object? 在Scala中构造/构建JavaBean对象的最简洁方法是什么? - What is the most concise way to construct/build JavaBean objects in Scala?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM