簡體   English   中英

如何在Java中將數組長度設置為字符串的大小並從字符串中引入字符

[英]How to set array length to the size of a string and bring in characters from the string in Java

嗨,我是Java的新手,正在從事一個項目,將一個字符串拆分成各個字符並發送給JavaFX。 我想最好的方法就是為此創建一個數組。

我想創建數組,使其具有至少等於字符串長度的索引,並且出現錯誤。 然后,我想將字符串的一部分從某個點發送到數組的末尾。 我想我可以將各個字母發送到JavaFX標簽和包裝盒。

public static void main(String[]args) {
    String gamePhrase = "Some Phrase here";
    String guessPhrase = gamePhrase.replaceAll("[a-zA-Z0-9]", "*"); 

    System.out.println(guessPhrase); 

    System.out.println(arraytest);

    char[] array2 =new char[gamePhrase.length()];

    guessPhrase.getChars (1,gamePhrase.length(),array2,0);

    System.out.println(array2);}
}

我在哪里錯呢? 為什么我不能使用string.length()功能? 有沒有人可以建議的更好的方法? 我不想使用toArray,因為數組將不包含所有字符。

任何幫助將非常感激。

您可以使用字符串.toCharArray()。

char[] array2=gamePhrase.toCharArray()

然后,所有字符串都將具有與getChars相同的getChars

希望這段代碼對您有所幫助。

    String str = "hello";
    char[] ch = new char[str.length()];
    ch = str.toCharArray();
    for(int i=0;i<ch.length;i++){
     //this will print all the char
     System.out.println("ch len == "+ ch[i]);
     //to select specific char
     if(ch[i] == 'l'){
         System.out.println("selected chars == "+ ch[i]);
     }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM