我有一个字符串,其中单词由一个或三个空格分隔。我正在尝试打印每 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标题有点乱,想不到更简单的了……