最多包含 n 个字符的子字符串

Substring contatining words up to n characters

我有一个字符串,我想获取最多包含 N 个字符的第一个单词。

例如:

String s = "This is some text form which I want to get some first words";

假设我想获取最多 30 个字符的单词,结果应如下所示:

This is some text form which

有什么方法吗?我不想重新发明轮子。

编辑:我知道 substring 方法,但它会断词。我不想得到类似

的东西

This is some text form whi 等等

用space ' '拆分你的字符串然后foreach substring将它添加到一个新字符串并检查新子字符串的长度是否超过或不超过限制。

您可以使用正则表达式来实现这一点。像下面这样的东西应该可以完成工作:

    String input = "This is some text form which I want to get some first words";
    Pattern p = Pattern.compile("(\b.{25}[^\s]*)");
    Matcher m = p.matcher(input);
    if(m.find())
        System.out.println(m.group(1));

这产生:

This is some text form which

正则表达式的解释可用here。我使用 25,因为前 25 个字符会导致子字符串损坏,因此您可以将其替换为您想要的任何值。

不用正则表达式也可以这样做

String s = "This is some text form which I want to get some first words";
// Check if last character is a whitespace
int index = s.indexOf(' ', 29-1);
System.out.println(s.substring(0,index));

输出为This is some text form which;

强制编辑:那里没有长度检查,所以请注意。