【问题标题】:Java Read How to read first word then the rest of an inputJava Read 如何读取第一个单词,然后读取输入的其余部分
【发布时间】:2013-02-15 12:34:02
【问题描述】:

我无法弄清楚如何读取输入行的其余部分。我需要标记第一个单词,然后可能将输入行的其余部分创建为一个完整的标记

public Command getCommand() 
{
    String inputLine;   // will hold the full input line
    String word1 = null;
    String word2 = null;

    System.out.print("> ");     // print prompt

    inputLine = reader.nextLine();

    // Find up to two words on the line.
    Scanner tokenizer = new Scanner(inputLine);
    if(tokenizer.hasNext()) {
        word1 = tokenizer.next();      // get first word
        if(tokenizer.hasNext()) {
            word2 = tokenizer.next();     // get second word
            // note: just ignores the rest of the input line.
        }
    }

    // Now check whether this word is known. If so, create a command
    // with it. If not, create a "null" command (for unknown command).
    if(commands.isCommand(word1)) {
        return new Command(word1, word2);
    }
    else {
        return new Command(null, word2); 
    }
}

输入:

take spinning wheel

输出:

spinning

期望的输出:

spinning wheel

【问题讨论】:

    标签: java token java.util.scanner tokenize


    【解决方案1】:

    使用split(String regex, int limit)

    String[] line = scan.nextLine().split(" ", 2);
    
    String firstWord = line[0];
    
    String rest= line[1];
    

    参考doc这里

    【讨论】:

      【解决方案2】:

      你也可以这样试试……

      String s = "This is Testing Result";
      System.out.println(s.split(" ")[0]);
      System.out.println(s.substring(s.split(" ")[0].length()+1, s.length()-1));
      

      【讨论】:

        【解决方案3】:

        或 -

        String inputLine =//Your Read line
        String desiredOutput=inputLine.substring(inputLine.indexOf(" ")+1)
        

        【讨论】:

          【解决方案4】:

          使用split()
          String[] line = scan.nextLine().split(" ");
          String firstWord = line[0];
          String secondWord = line[1];

          这意味着您需要在空格处拆分行并将其转换为数组。现在使用 yhe 索引你可以得到任何你想要的词

          【讨论】:

            猜你喜欢
            • 2021-12-22
            • 1970-01-01
            • 2015-04-11
            • 1970-01-01
            • 2013-07-08
            • 1970-01-01
            • 1970-01-01
            • 2019-09-09
            • 2022-01-25
            相关资源
            最近更新 更多