0

我有一个关于在 Java 中制作字符串数组的问题。我想创建一个字符串数组,它将在字符串数组的每个隔间中存储一个特定的单词。例如,如果我的程序扫描What is your deal?了我想要单词Whatandyour出现在数组中,以便稍后显示它。

我该如何编码?另外,我如何显示它System.out.println();

好吧,到目前为止,这是我的代码:

import java.util.Scanner;
import java.util.StringTokenizer;

public class OddSentence {

    public static void main(String[] args) {

        String sentence, word, oddWord;
        StringTokenizer st;

        Scanner scan = new Scanner (System.in);


        System.out.println("Enter sentence: ");
        sentence = scan.nextLine();

        sentence = sentence.substring(0, sentence.length()-1);
        st = new StringTokenizer(sentence);

        word = st.nextToken();


        while(st.hasMoreTokens()) {
            word = st.nextToken();
            if(word.length() % 2 != 0) 

        }

        System.out.println();
    }
}

我希望我的程序计算一个句子中的每个单词。如果单词有奇数个字母,就会显示出来。

4

4 回答 4

2

根据您单独提供的内容,我会说使用#split()

String example = "What is your deal?"
String[] spl = example.split(" ");
/*
  args[0] = What
  args[1] = is
  args[2] = your
  args[3] = deal?
*/

要将数组作为一个整体显示,请使用Arrays.toString(Array);

System.out.println(Arrays.toString(spl));
于 2014-04-09T22:33:48.247 回答
1

阅读和拆分使用String.split()

final String input = "What is your deal?";
final String[] words = input.split(" ");

要将它们打印到例如命令行,请使用循环:

for (String s : words) {
    System.out.println(s);
}

或者在使用 Java 8 时使用Stream

Stream.of(words).forEach(System.out::println);
于 2014-04-09T22:34:35.637 回答
0

input成为您的输入字符串。然后:

String[] words = input.split(" ");
于 2014-04-09T22:33:47.183 回答
0

我同意其他人所说的,您应该使用 String.split(),它将提供的字符上的所有元素分开并将每个元素存储在数组中。

String str = "This is a string";
String[] strArray = str.split(" ");   //splits at all instances of the space & stores in array
for (int i = 0; i < strArray.length(); i++) {
  if((strArray[i].length() % 2) == 0) {  //if there is an even number of characters in the string
    System.out.println(strArray[i]);     //print the string
  }
}

输出:

这是字符串

如果要在字符串包含奇数个字符时打印字符串,只需更改if((strArray[i].length() % 2) == 0)if((strArray[i].length() % 2) != 0)

这将为您提供a作为输出(字符串中唯一具有奇数个字符的单词)。

于 2014-04-10T00:09:42.037 回答