Search code examples
javaarraysstringstring-length

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.


Solution

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