Looking this code
看这段代码
String input="I use this method";
String word=input.replaceAll(" ","/");
char buf[]=word.toCharArray();
but i want to another method to doing this?
但我想要另一种方法来做到这一点?
2 个解决方案
#1
This is the easiest way I have found to convert a string including white spaces to a char array in java.
这是我发现将包含空格的字符串转换为java中的char数组的最简单方法。
String input = "I use this method";
char[] buf = input.toCharArray();
It looks like you are doing it right, but taking out all of the white space with the replaceAll(" ", "/")
看起来你做得对,但用replaceAll(“”,“/”)取出所有的空白区域
#2
From your question I'm assuming you want to save the string without truncating the whitespace in a char array.
从你的问题我假设你想保存字符串而不截断char数组中的空格。
If your remove the line " String word=input.replaceAll(" ","/"); " from your code.Then your code will work perfectly fine.PFB a sample code which might help you to understand this better
如果您从代码中删除“String word = input.replaceAll(”“,”/“);”,那么您的代码将完全正常工作.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
}
}
#1
This is the easiest way I have found to convert a string including white spaces to a char array in java.
这是我发现将包含空格的字符串转换为java中的char数组的最简单方法。
String input = "I use this method";
char[] buf = input.toCharArray();
It looks like you are doing it right, but taking out all of the white space with the replaceAll(" ", "/")
看起来你做得对,但用replaceAll(“”,“/”)取出所有的空白区域
#2
From your question I'm assuming you want to save the string without truncating the whitespace in a char array.
从你的问题我假设你想保存字符串而不截断char数组中的空格。
If your remove the line " String word=input.replaceAll(" ","/"); " from your code.Then your code will work perfectly fine.PFB a sample code which might help you to understand this better
如果您从代码中删除“String word = input.replaceAll(”“,”/“);”,那么您的代码将完全正常工作.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
}
}