[英]Get substring from string using start and end white spaced position
I have a string and I wanted to get the substring based on the start and end position of the words.我有一个字符串,我想根据单词的开始和结束位置获取子字符串。
I have written it and it works fine, but I wanted to know if there is a clean way using any library to acheive the same我已经写了它并且它工作正常,但我想知道是否有使用任何库来实现相同的干净方法
String keyword = "My test string value"
int start = 1;
int end = 2;
String[] arr = keyword.split("\\s+");
StringBuilder sb = new StringBuilder();
for(int i=start;i<=end;i++){
sb.append(arr[i]).append(" ");
}
return sb.toString().trim(); // returns "test string"
I do not know about any libraries, but you could replace我不知道任何图书馆,但你可以替换
String[] arr = keyword.split("\\s+");
StringBuilder sb = new StringBuilder();
for(int i=start;i<=end;i++){
sb.append(arr[i]).append(" ");
}
return sb.toString().trim();
with和
return Arrays.stream(keyword.split("\\s+"))
.limit(end+1)
.skip(start)
.collect(Collectors.joining(" "));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.