如何在 java 的 char 数组中存储带空格的字符串值?

How can i store string value with whitespace in char array in java?

查看此代码

        String input="I use this method";
        String word=input.replaceAll(" ","/");
        char buf[]=word.toCharArray();

但我想用另一种方法来做到这一点?

这是我发现的将包含白色 spaces 的字符串转换为 java 中的字符数组的最简单方法。

String input = "I use this method";
char[] buf = input.toCharArray();

看起来你做得对,但是用 replaceAll(" ", "/")

去掉了所有的白色 space

根据你的问题,我假设你想保存字符串而不截断 char 数组中的空格。

如果您从 code.Then 中删除行“ String word=input.replaceAll(" ","/"); ",您的代码将起作用完美 fine.PFB 一个示例代码,可以帮助您更好地理解这一点

public static void main(String[] args) 
  {
       String input="I use this method";
       System.out.println(input.length()); //length of string before converting to char array
       //String word=input.replaceAll(" ","/");
       char buf[]=input.toCharArray();
       System.out.println(buf.length);//length of string after converting to char array
       for(int i=0;i<buf.length;i++){
       System.out.print(buf[i]); /// Print the values in char array
       }
  }