gpt4 book ai didi

java - 确定用户输入的句子中的第二个单词

转载 作者:行者123 更新时间:2023-12-02 06:42:49 24 4
gpt4 key购买 nike

我正在尝试查找句子中输入的第二个单词。我已经确定了第一个单词,但无法找到如何获得第二个单词。这是我尝试过的:

    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);

最佳答案

您正在将第二个单词从第一个空格移到第​​一个空格(它将为空)。我建议你一直读到第二个空格或结尾。

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

如果你可以使用 split,你就可以做到

 String[] words = strSentence.split(" ");
String word1 = words[0];
String word2 = words[1];

关于java - 确定用户输入的句子中的第二个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18969168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com