[英]Splitting a string to the nth delimiter
I am trying to split a string, keep the delimiters and save to a new string based on the Nth delimiter. 我正在尝试拆分字符串,保留定界符并基于第N个定界符保存到新字符串。 For example. 例如。
String s = "HELLO-WORLD-GREAT-DAY"
I would like to store HELLO-WORLD-GREAT
and chop off the -DAY
. 我想存储HELLO-WORLD-GREAT
并砍掉-DAY
。
I can capture the individual elements using split[x]
but I cant seem to figure out the best way to assert this to a new string
to be used later on. 我可以使用split[x]
捕获单个元素,但似乎无法找出将其声明为新string
以供以后使用的最佳方法。
Any idea's folks? 有什么主意吗?
I have tried to use split last and first etc. 我尝试过使用split last和first等。
I need to be able to capture first three elements of the input string 我需要能够捕获输入字符串的前三个元素
Split and combine: 拆分并合并:
public String removeLast(String input) {
//Split your input
String[] parts = input.split("-");
//Combine to a new string, leaving out the last one
String output = parts[0];
for (int i = 1; i < parts.length - 1; i++) {
output += "-" + parts[i];
}
return output;
}
Try the following: 请尝试以下操作:
public String removeLast(String target, String delimiter) {
int pos = target.lastIndexOf(delimiter);
return pos == -1 ? target : target.substring(0, pos);
}
You would call the method like this: 您将这样调用方法:
String result = removeLast("HELLO-WORLD-GREAT-DAY", "-");
Two easy ways I can think of: 我可以想到两种简单的方法:
String hw = "HELLO-WORLD-GREAT-DAY"
def result = hw - hw.substring(hw.lastIndexOf('-'))
And String.join
with split
's result: 和String.join
与split
的结果:
def result = String.join('-', hw.split('-')[0..-2])
有了groovy,您可以做到
"HELLO-WORLD-GREAT-DAY".split('-')[0..-2].join('-')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.