class wordSep{
public static void main(String args[]){
String line = "The world is full of strangers";
String word = line.substring(0,line.indexOf(" "));
int index = line.length()-1;
while(index>=0){
System.out.println(word);
line = line.substring(line.indexOf(" ") + 1) + " ";
word = line.substring(0,line.indexOf(" "));
index--;
}
}
}
输出结果如下:
The
world
is
full
of
strangers
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
\\empty line
我认为这与我的while循环的条件有关。我需要没有那些空行的输出..请帮助,谢谢。
答案 0 :(得分:2)
将while(index>=0)
替换为while(!word.isEmpty())
并删除index
答案 1 :(得分:1)
很高兴你的问题得到了解决但是如果你尝试在代码中使用一些内置函数(如 String.split())和库会很好,因为它可以减少很多处理和使您的代码更健壮,独立于字符串长度和其他参数。
您的代码可以优化到此级别......
class wordSep{
public static void main(String args[]){
String line = "The world is full of strangers";
String[] word = line.split(" ");
for(String str: word){
System.out.println(str);
}
}
}
输出 -
The
world
is
full
of
strangers
现在你也可以使用String Tokenizer但不建议再使用它......
阅读本文 - > to completely understand how to split Strings in Java on some character, or using some Regex and other parameters 强>
答案 2 :(得分:0)
学家幸运的是,你可以减少sop的数量和尺寸,如下所示:
class Extract
{
void Substring()
{
String s = "The World is Full of Strangers.";
s = s + " ";
int idxOfNextWord = 0;
for(int i = 0; i < s.length(); i++)
{
if(s.charAt(i)== ' ')
{
System.out.println(s.substring(idxOfNextWord, i));
idxOfNextWord = i+1;
}
}
}
}
答案 3 :(得分:-1)
即使您似乎已经解决了问题,仍然会发布此答案。我相信你的代码可以最小化到这几行:
String line = "The world is full of strangers";
int idxOfNextWord = 0;
for (int i = 0; i < line.length(); i++) {
if(line.charAt(i)==' ') {
System.out.println(line.substring(idxOfNextWord, i));
idxOfNextWord = i+1;
}
}
System.out.println(line.substring(idxOfNextWord));