0

我有一个字符串,其中单词由一个或三个空格分隔。我正在尝试打印每 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
    }

}

输出:一一一

此时start=11,length=11,threeSpaces=11!三个空格是问题所在,我希望该值是新开始索引(11)中下一组 3 个空格“”的索引...任何输入表示赞赏...

PS标题有点乱,想不到更简单的了……

4

4 回答 4

3

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

String[] myWords = sentence.split("   ");
for (String word : myWords) {
    System.out.println(word);
}
于 2013-10-19T16:40:57.353 回答
2

您必须将起始索引指定为start + 1,否则您将在 中获得相同 3 个空格的索引sentence

threeSpaces = sentence.indexOf("   ", start + 1);

但是你必须做更多的任务。你需要" "在实际调用之前检查索引substring,因为当没有更多" "时,索引将是-1,你会得到StringIndexOutOfBounds异常。为此,您可以将while循环条件更改为:

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

这将停止while循环,一旦 3 个空格的索引变为-1,这意味着不再有 3 个空格。


解决此问题的更好方法是split使用 3 个空格:

String[] words = sentence.split("\\s{3}");

for (String word : words) {
    System.out.println(word);
}
于 2013-10-19T16:41:37.337 回答
1

I have a string where words are either seperated by one or three spaces. I am tryng to print the set of words that are seperated by every 3 spaces.

您应该使用String#split3 个空格:

String[] tokens = sentence.split(" {3}");
于 2013-10-19T16:41:27.220 回答
0

谢谢大家,拆分看起来很容易:字符串短语=“一一三一一一三三一一三三三一一一”;字符串[] split2 = 短语.split(" "); for(字符串三:split2)System.out.println(三);

输出:一一三一一一三三一一三三三一一一

于 2013-10-19T17:14:03.273 回答