0

4 つの単語からなる文を個々の単語に分割したいと考えています。しかし、文の最初のスペースと停止の後から開始し、次のスペースに移動するように指示する方法がわかりません。

import java.util.Scanner;
public class arithmetic {
    public static void main(String[] args) {
    Scanner in = new Scanner(System.in)

    String sentence;
    String word1, word2, word3, word4;
    int p, p2;

    System.out.print("Enter a sentence with 4 words:");
    sentence = in.nextLine();

    p = sentence.indexOf(" ");

    word1 = sentence.substring(0,p)+(" ");
    word2 = sentence.substring()(" ");
    word3 = sentence.substring()+(" ");
    word4 = sentence.substring()+(" ");

    sentence = word1+word2+word3+word4;

    System.out.println(sentence);
4

2 に答える 2

0

String.split()次のようにメソッドを使用することもできます。

String[] parts = sentence.split("\\s");

Chris のアプローチとまったく同じ結果が得られます。

于 2013-09-12T01:10:25.993 に答える
0

これはStringTokenizerの仕事のように思えます!

words = new StringTokenizer(sentence).split("\\s");

これで、単語に含まれる文字列の配列ができました。これらを使って、別の文に変換するなど、好きなことを行うことができます。

于 2013-09-11T23:32:33.830 に答える