简体   繁体   English

如何在Java中将数组长度设置为字符串的大小并从字符串中引入字符

[英]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. 嗨,我是Java的新手,正在从事一个项目,将一个字符串拆分成各个字符并发送给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. 我想我可以将各个字母发送到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);}
}

Where am i going wrong in this ? 我在哪里错呢? Why cant I use the the string.length() feature? 为什么我不能使用string.length()功能? Is there are better way any one could suggest? 有没有人可以建议的更好的方法? I dont want to use the toArray as the array will not contain all characters. 我不想使用toArray,因为数组将不包含所有字符。

Any help would be much appreciated. 任何帮助将非常感激。

You can use the string .toCharArray(). 您可以使用字符串.toCharArray()。

char[] array2=gamePhrase.toCharArray()

Then you will have the same as getChars for all the string. 然后,所有字符串都将具有与getChars相同的getChars

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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