Java - 仅使用 .substring 过程在字符串中查找多个单词

标签 java string

我正在尝试使用空格“”来分隔用户输入的字符串中的单词。对于此示例,用户输入字符串可能是“Random Access Memory”或“Java Development Kit”。无论输入的字符串如何,空格都会分隔每个单词。除此之外,我不能使用 .split 或数组,因为这些是我迄今为止找到的最常见的解决方案。只允许使用 .substring。在我失败的尝试中,我只能获得第一个输入的单词(例如“随机”),但不能将第二个和第三个单词分开(例如“访问内存”)。我不会公布我失败的尝试,但我想问你是否可以提供分隔输入的第二个和第三个单词的代码?谢谢。

附言我知道这是用来创建首字母缩略词的,我可以做那部分,只需要识别每个子字符串。

  import javax.swing.*;
  public class ThreeLetterAcronym
  {
     public static void main(String[] args)
     {

        String wordsInput, initialInput;
        String first = "";
        String second = "";
        String third = "";

        int firstWord;
        int secondWord;
        int wordLength;
        int secondWordLength;

        char c;

        wordsInput = JOptionPane.showInputDialog(null, "Please enter three words");
        initialInput = wordsInput;
        wordLength = wordsInput.length();
        firstWord = 0;
        secondWord = 0;


        while(firstWord < wordsInput.length()) 
              {
               if(wordsInput.charAt(firstWord) == ' ') 
               {
                  first = wordsInput.substring(0,firstWord);
                  second = wordsInput.substring(firstWord + 1, wordsInput.length());
  //I know that this is the spot where the last two words are displayed in the output, this is
  //the closest I have been to displaying anything relevant.
                  firstWord = wordsInput.length();

               }
                  ++firstWord;

              }
        JOptionPane.showMessageDialog(null, "Original phrase was: " 
           + initialInput + "\nThree letter acronym is: " + first + second);
        }
  }

最佳答案

只是在不使用(奇怪地)使用 Spring.split 的情况下将单词分开:

String myString = "Random Access Memory";

int begin = 0;
int end;
while((end = myString.indexOf(" ", begin)) != -1) {
    System.out.println(myString.substring(begin, end));
    begin = end + 1;
}
System.out.println(myString.substring(begin));

关于Java - 仅使用 .substring 过程在字符串中查找多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22886584/

相关文章:

java - 为什么这个 Java Switch-Case 不起作用?

C++ - 将 null 分配给 std::string

Java添加对象到ArrayList错误

java - 在 Netbeans Java 应用程序中关闭后保存面板位置

javascript - 连接字符串和 <a href =""></a>

java - 插入二维字符串数组时出现空指针异常

java - 如何在 Java 中构建 SPARQL 查询?

java - 如何在文本区域中打印对象结果?

java - 在java中使用正则表达式匹配大文本中的内容

java - 无法清除 hibernate 缓存