搜索字符串中的第二个单词

时间:2016-12-11 14:49:24

标签: java

我是java的新手,我正在做这个练习,搜索字符串中的第二个单词,例如,如果字符串是"我喜欢java"该计划应该回归"爱"。

这是我的代码:

import java.util.*;

// This program returns the second word of a string
public class SecondWord{
    public static void main(String[]args){
        Scanner in = new Scanner(System.in);
        System.out.println("String: ");
        String x = in.nextLine();
        int pos = x.indexOf(" ");
        int pos1 = x.indexOf(" ", pos);
        String second = x.substring(pos, pos1);
        System.out.println(second);
    }
}

它编译,但它什么也没有返回。怎么了?

2 个答案:

答案 0 :(得分:3)

当您获得" "的下一个索引时,您应该在最后一个索引中增加1。

更改此

int pos1 = x.indexOf(" ", pos);

int pos1 = x.indexOf(" ", pos+1);

注意

在开始使用子字符串删除额外空格或trim时,您应该将位置增加1。

String second = x.substring(pos+1, pos1);

替代解决方案

一种更好的方法是做同样的事情

String x = in.nextLine();
System.out.println(x.split(" ")[1]);

" "拆分字符串并打印第二个元素。

答案 1 :(得分:1)

我知道这个线程已经很老了,但是我遇到了同样的问题。感谢您使用split方法的解决方案,它非常有帮助。但是,我注意到有一条评论说,如果只输入两个单词,带有pos + 1修复程序的原始代码将不起作用,并且我还发现,仅输入一个单词将不起作用。这使我想知道,如果只有一个或两个单词,是否可以使用这种方法找到第二个单词而没有任何错误。这是我想出的:

//For keyboard input
import java.util.Scanner;

// This program returns the second word of a string
public class SecondWord {
    public static void main(String[]args) {

        //Creates a scanner object for keyboard input
        Scanner in = new Scanner(System.in);

        //Gets a string from the user
        System.out.print("String: ");
        String x = in.nextLine();

        //If the string contains more than one word
        if (x.contains(" ")) {
            //Finds the position of the first space, adds one to it to find the position of the first character of the second word
            int pos = x.indexOf(" ") + 1;

            //Replace the first space with a different character so the program can test if it has a second space
            char[] chars = x.toCharArray();
            chars[pos - 1] = 'a';
            x = String.valueOf(chars);

            //If there is a space after the second word
            if (x.contains(" ")) {

                //Finds the position of the space after the second word
                int pos1 = x.indexOf(" ", pos);

                //Gets the second word
                String second = x.substring(pos, pos1);

                //Displays the second word
                System.out.println(second);

                //If there is not a space after the second word
            } else {

                //Add a space to the end
                x += " ";

                //Finds the position of the space after the second word
                int pos1 = x.indexOf(" ", pos);

                //Gets the second word
                String second = x.substring(pos, pos1);

                //Displays the second word
                System.out.println(second);
            }
        } 
    }
}