有没有更简单的方法来编写这个java程序?

时间:2014-09-01 17:20:06

标签: java

该程序将句子中的单词分开。请不要使用“拆分”方法,因为它超出了我们学校的课程。请不要吝啬地回复。

    int length=0;
    int x=sent.length();
    int a;
    int b=0;
    for(a=0;a<x;a++)
    {
        char z=sent.charAt(a);
        if(z==' ')
        {
            String hell=sent.substring(b,a);
            System.out.println(hell);
            b=b+hell.length()+1;
        }
    }

3 个答案:

答案 0 :(得分:2)

我个人会使用java.util.Scanner。如果这超出了你学校的范围,找一所新学校!

import java.util.Scanner;

public class Example {

    public static void main(String[] args) {
        String sentence = "Hello world of overflowing   stacks";

        Scanner sc = new Scanner(sentence);
        while (sc.hasNext())
        {
            System.out.println(sc.next());
        }
    }
}

输出:

Hello
world
of
overflowing
stacks

答案 1 :(得分:1)

更简单的方法是

for(char ch : sent.toCharArray()) {
    if (ch == ' ') ch = '\n';
    System.out.print(ch);
}

答案 2 :(得分:0)

您可以使用indexOf和子字符串来执行此操作:

int index= word.indexOf(" ");
do{
  System.out.println(word.substring(0, index));
  word = word.substring(index + 1);
  index = word.indexOf(" ");
} while (index != -1);
相关问题