0

好的,首先我想说我是 Java 开发的新手......考虑到这一点,我目前正在尝试使 tryWord 的值包含空格,而不是在 s 中的空格的情况下包含破折号。谁能帮我?

    String tryWord = "";
    for (int i = 0; i < s.length(); i++) {
        tryWord += "-";
    }
    System.out.println(s + tryWord);

Value for s
------------
private static String randomOutput() {
    String array[] = new String[10];
    array[0] = "Hamlet";
    array[1] = "Mysts of Avalon";
    array[2] = "The Iliad";
    array[3] = "Tales from Edger Allan Poe";
    array[4] = "The Children of Hurin";
    array[5] = "The Red Badge of Courage";
    array[6] = "Of Mice and Men";
    array[7] =  "Utopia"; 
    array[8] =  "Chariots of the Gods";
    array[9] =  "a Brief History of Time";

    ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));
    Collections.shuffle(list);
    String s = list.get(0);
    return s;
}
4

4 回答 4

2

你可以在java中使用replace or replaceAll,它会解决问题

tryWord = s.replaceAll("\\s", "-");
于 2013-04-24T13:56:47.737 回答
0
   tryWord += s.charAt(i) == ' ' ? " " : "-";

这称为三元表达式... ? ... : ...,一种 if ith char is space then space else dash。

于 2013-04-24T13:59:36.980 回答
0

用这个:

 tryWord.replace(oldChar, newChar);
于 2013-04-24T13:57:48.307 回答
0

试试这个:

if (s.charAt(i) == ' ') {
   tryWord += ' ';
} else {
   tryWord += '-';
}
于 2013-05-04T19:05:11.687 回答