Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

java - 从字符串数组中提取单词(Extracting words from a String array)

I'm trying to extract a two worded string in the exact same way but all I'm getting is only the first word as the output.

(我试图以完全相同的方式提取两个单词的字符串,但是我得到的只是输出的第一个单词。)

public class name {
    public static void main(String[] args)throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        String []arr = new String[10];
        String name, str = " ";
        int k = 0;
        System.out.println("Enter Name");
        name = in.readLine();
        for(int i = 0; i < name.length(); i++) {
            if(name.charAt(i) != ' ') {
                str = str + name.charAt(i);
            }
            else {
                arr[k++] = str;
                str = " ";
            }
        }
        for(int i = 0; i < k; i++)
        System.out.println(arr[i]);

    }
}
  ask by coolhack7 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the question is already answered.

(我认为这个问题已经回答。)

But instead of walking through the characters of the string it is better to use the standard Java library as follows:

(但是,与其遍历字符串的字符,不如使用标准的Java库,如下所示:)

name = in.readLine();
if (name != null && !"".equals(name)) {
    String[] arr = name.split("\s+");
    for (int i = 0; i < arr.length; i++)
        System.out.println(arr[i]);
}

The split() method does what you're trying to program yourself.

(split()方法可以完成您要编程的工作。)

The string \\s+ ist a regular expression which represents one or more space characters (space, newline, ...).

(字符串\\s+是一个正则表达式,代表一个或多个空格字符(空格,换行符,...)。)

You could also use " " instead, but in this case your input must contain only one space character.

(您也可以改用" " ,但是在这种情况下,您的输入必须仅包含一个空格字符。)

Example:

(例:)

System.out.println("Enter Name");

(System.out.println(“输入名称”);)

Input:

(输入:)

firstname secondname         lastname

output:

(输出:)

firstname
secondname
lastname

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...