Java 使用3个空格作为返回索引的指定字符串的第一个匹配项获取子字符串

Java 使用3个空格作为返回索引的指定字符串的第一个匹配项获取子字符串,java,regex,string,Java,Regex,String,我有一个字符串,其中单词被一个或三个空格分隔。 我正在尝试打印每3个空格分隔的单词集。 我得到了第一组达到3个空格的单词,并进入了一个无限循环: String sentence = "one one one three three one three one"; int lenght=0; int start=0; int threeSpaces = sentence.indexOf(" ");//get index where 1st 3 spaces

我有一个字符串,其中单词被一个或三个空格分隔。 我正在尝试打印每3个空格分隔的单词集。 我得到了第一组达到3个空格的单词,并进入了一个无限循环:

String sentence = "one one one   three   three one   three one";
    int lenght=0;
    int start=0;
    int threeSpaces = sentence.indexOf("   ");//get index where 1st 3 spaces occur

    while (lenght<sentence.length()) {



    String word = sentence.substring(start, threeSpaces);//get set of words separated by 3 spaces
    System.out.println(word);
    start=threeSpaces;//move starting pos
    length=threeSpaces;//increase length 
    threeSpaces= sentence.indexOf("   ", start);//find the next set of 3 spaces from the last at index threeSpaces

    }//end while
    }
String-station=“一一一三三一三一”;
整数长度=0;
int start=0;
int-threeSpaces=句子.indexOf(“”)//获取前3个空格所在的索引

而(lenght这可以通过以下代码更简单地完成:

String[] myWords = sentence.split("   ");
for (String word : myWords) {
    System.out.println(word);
}

使用以下代码可以更简单地完成此操作:

String[] myWords = sentence.split("   ");
for (String word : myWords) {
    System.out.println(word);
}
我有一个字符串,其中单词由一个或三个分隔
空格。我正在尝试打印每3个空格分隔的单词集。

您应该使用带有3个空格的
String#split

String[] tokens = sentence.split(" {3}");
我有一个字符串,其中单词由一个或三个分隔
空格。我正在尝试打印每3个空格分隔的单词集。

您应该使用带有3个空格的
String#split

String[] tokens = sentence.split(" {3}");

您必须将起始索引设置为
start+1
,否则您将获得
句子中相同3个空格的索引:

threeSpaces = sentence.indexOf("   ", start + 1);
但是您还需要做更多的工作。在实际调用
子字符串之前,您需要检查
的索引,因为当没有更多的
,索引将为
-1
,您将获得
StringIndexOutOfBounds
异常。为此,您将
while
循环条件更改为:

while (lenght<sentence.length() && threeSpaces != -1)

您必须将起始索引设置为
start+1
,否则您将获得
句子中相同3个空格的索引:

threeSpaces = sentence.indexOf("   ", start + 1);
但是您还需要做更多的工作。在实际调用
子字符串之前,您需要检查
的索引,因为当没有更多的
,索引将为
-1
,您将获得
StringIndexOutOfBounds
异常。为此,您将
while
循环条件更改为:

while (lenght<sentence.length() && threeSpaces != -1)

谢谢大家,split看起来像是一个游戏: 字符串短语=“一一三一一三三一一一三三三一一”; String[]split2=短语.split(“”); 用于(字符串三:拆分2) 系统输出打印(三)

输出: 11 三 111 33 111 333
一个一个

谢谢大家,split看起来像一个围棋: 字符串短语=“一一三一一三三一一一三三三一一”; String[]split2=短语.split(“”); 用于(字符串三:拆分2) 系统输出打印(三)

输出: 11 三 111 33 111 333
使用
String[]wordsWith3SpacesBetween=句子。拆分(“3literalspaces”);
(对3literalspaces使用3个空格-空格不好发布)使用
String[]wordsWith3SpacesBetween=句子。拆分(“3literalspaces”);
(对3literalspaces使用3个空格-空格不好发布)怎么样我试着打印每3个空格分隔的单词集。-你错过了问题中的第二句。我试着打印每3个空格分隔的单词集。-你错过了问题中的第二句。