【问题标题】:Is there a way to create a char array of the same character based on how many letters there are in a string in Java?有没有办法根据Java中字符串中有多少个字母来创建相同字符的char数组?
【发布时间】:2019-09-09 21:03:50
【问题描述】:

我正在尝试用 Java 创建一个刽子手游戏,我想知道是否有一种方法可以根据字符串中有多少个字母来创建相同字符的 char array
例如,如果用户输入了5 letter word,则使用5 underscores 创建char array

这是我迄今为止尝试过的无济于事:

    System.out.println("Enter a word to guess");
    String wordToGuess = input.nextLine();

    String array[] = {"_", "_", "_",};
    char underscore[] = array.toCharArray();

我得到的错误信息是:

Cannot invoke toCharArray() on the array type String[]

【问题讨论】:

    标签: java arrays string char


    【解决方案1】:

    最简单的方法如下

    char[] chars = new char[userinput.length()] ;
    Arrays.fill(chars, '_') ;
    

    【讨论】:

      【解决方案2】:

      试试这个:

      //creates a char array the same size as the word the user has given
      char[] underscore = new char[wordToGuess.length()];
      //fills all the items in the underscore array with '_' character 
      Arrays.fill(underscore, '_');
      

      【讨论】:

        【解决方案3】:
        String[] sArray = {"_", "_", "_",};
        String s = "";
        for (String n:sArray)
        s+= n;
        char[] c = s.toCharArray();
        

        【讨论】:

        • 包含解释将提高您的回答质量。
        【解决方案4】:

        toCharArray() 方法仅适用于 String,不适用于 String[]。这就是发生错误的原因。

        您可以连接数组的所有部分,然后转换为字符。例如。 String.join(“”, array).toCharArray()

        【讨论】:

          【解决方案5】:

          您可以通过将文本转换为 CHAR ARRAY 来获取字符串的长度并对其进行管理,如下例所示:

          public static void main(String[] args) {
              String testString = "This Is Test";
              int stringLength = testString.length(); //Maybe you can use this.
              char[] arrayName = testString.toCharArray(); //And here you can manage your array
          
              for (int i = 0; i<=testString.length()) {
                  System.out.println(char[i]);
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-06-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-06-02
            • 2014-08-23
            • 2019-11-03
            相关资源
            最近更新 更多