简体   繁体   English

使用开始和结束空白位置从字符串中获取子字符串

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

相关问题 如何从 substring 中删除 Substring 开始直到 Java 中的字符串结尾 - How to remove Substring from substring start until the end of the string in Java 如何获取字符串中行的开始位置和结束位置 - How to get start position and end position of line in a string 获取单词开始和结束 position - Get the word start and end position 在没有小写字母的字符串结尾获取子字符串 - Get substring at end of string that has no lowercase letters 多次查找字符串开始和结束位置 - Find String Start and End position multiple times 正则表达式通过用运算符(!,&,((),|)拆分所有字符串的开始和结束位置来获取String数组在Java中 - Regex to get String array by splitting with operators ( ! , & , ( , ) , | ) with all string's start and end position In Java 在带有分隔符的String中查找和删除subString(start:55555,end:\\ n) - Find and delete subString in a String with delimiters (start: 55555, end: \n) 查找“开始”字符串和3个可能的“结束”字符串之一之间的最长子字符串 - Finding the longest substring between a “start” string and one of 3 possible “end” strings 从Java中的String获取子串 - Get Substring from a String in Java 如何获取子串的位置 - How To Get The Position of A Substring
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM