0

文に入力された 2 番目の単語を見つけようとしています。最初の単語を決定しましたが、2 番目の単語だけを取得する方法を見つけるのに苦労しています。これは私が試したことです:

    String strSentence = JOptionPane.showInputDialog(null,
            "Enter a sentence with at" + " least 4 words",
            "Split Sentence", JOptionPane.PLAIN_MESSAGE);

    int indexOfSpace = strSentence.indexOf(' ');

    String strFirstWord = strSentence.substring(0, indexOfSpace);
/*--->*/String strSecondWord = strSentence.substring(indexOfSpace, indexOfSpace);
    Boolean blnFirstWord = strFirstWord.toLowerCase().equals("hello");
    Boolean blnSecondWord = strSecondWord.toLowerCase().equals("boy");

    JOptionPane.showMessageDialog(null, "The sentence entered: " + strSentence 
            + "\nThe 1st word is " + strFirstWord
            + "\nThe 2nd word is " + strSecondWord
            + "\nIs 1st word: hello? " + blnFirstWord
            + "\nIs 2nd word: boy? " + blnSecondWord);
4

5 に答える 5

1

最初のスペースから最初のスペースへの 2 番目の単語を取得しています (空になります)。2 番目のスペースまたは最後まで取ることをお勧めします。

 int indexOfSpace2 = = strSentence.indexOf(' ', indexOfSpace+1);
 String strSecondWord = strSentence.substring(indexOfSpace+1, indexOfSpace2);

分割を使用できる場合は、次のことができます

 String[] words = strSentence.split(" ");
 String word1 = words[0];
 String word2 = words[1];
于 2013-09-23T21:28:10.177 に答える
1
int indexOfSpace = strSentence.indexOf(' ');
String strFirstWord = strSentence.substring(0, indexOfSpace);
strSentence = strSentence.substring(indexOfSpace+1);
indexOfSpace = strSentence.indexOf(' ');
String strSecondWord = strSentence.substring(0, indexOfSpace);
strSentence = strSentence.substring(indexOfSpace+1);
indexOfSpace = strSentence.indexOf(' ');
String strThirdWord = strSentence.substring(0, indexOfSpace);
于 2013-09-23T21:28:54.920 に答える
0

最初の単語は、文頭と最初のスペースの間のテキストとして定義されますよね? それでString strFirstWord = strSentence.substring(0, indexOfSpace);、あなたのためにそれを手に入れます。

同様に、2 番目の単語は、最初のスペースと 2 番目のスペースの間のテキストとして定義されます。 String strSecondWord = strSentence.substring(indexOfSpace, indexOfSpace);最初のスペースと最初のスペース (空の文字列) の間のテキストを検索しますが、これは必要なものではありません。最初のスペースと2 番目のスペースの間にテキストが必要です...

于 2013-09-23T21:28:53.217 に答える
0

私は正規表現を使用します:

String second = input.replaceAll("^\\w* *(\\w*)?.*", "$1");

これは、入力全体を照合しながら 2 番目の単語をキャプチャし、一致したもの (つまりすべて) をグループ 1 でキャプチャされたものに置き換えることによって機能します。

重要なことに、正規表現はすべてがオプションになるように作成されています。つまり、2 番目の単語がない場合、結果は空白になります。これは、空白入力のエッジ ケースでも機能します。

もう 1 つの利点は、1 行だけであることです。

于 2013-09-23T21:30:48.617 に答える
0

クラスsplit()のメソッドを使用できます。Stringパターンを使用して文字列を分割します。例えば:

String strSentence = "word1 word2 word3";
String[] parts = strSentence.split(" ");

System.out.println("1st: " + parts[0]);
System.out.println("2nd: " + parts[1]);
System.out.println("3rd: " + parts[2]);
于 2013-09-23T21:31:10.743 に答える