简体   繁体   中英

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

Hi I am new to Java and am working on a project to get a string split up into individual characters and sent to JavaFX. I imagine the best way is to create an Array for this.

I want to create the array so it has an index of at least the the length of the string and I am getting an error. I then want to send part of the string from a certain point to the end of it to the array. I imagine then I can send the individual letters to JavaFX labels and boxes.

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);}
}

Where am i going wrong in this ? Why cant I use the the string.length() feature? Is there are better way any one could suggest? I dont want to use the toArray as the array will not contain all characters.

Any help would be much appreciated.

You can use the string .toCharArray().

char[] array2=gamePhrase.toCharArray()

Then you will have the same as getChars for all the string.

I hope this code will help you.,

    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]);
     }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM