Java-将字符串的字符存储在数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40789233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java-Storing characters of a string in an array
提问by Tanz
for (int j = 0; j <= l - 1; j++)
{ char c1 = str.charAt(j);
n[j] = c1;
}
//It is showing error-arrayIndexoutofbounds
'str' is an inputted string and 'l' is the length of the string str. I have to store all its character in an array and the array 'n' is of char type I have tried to store it by for loop but its showing error . Please help me out. Just remove that equal to sign in ur loop it will only be less than
'str' 是输入的字符串,'l' 是字符串 str 的长度。我必须将它的所有字符存储在一个数组中,并且数组 'n' 是 char 类型我试图通过 for 循环存储它,但它显示错误。请帮帮我。只需删除等于在您的循环中签名它只会小于
回答by f1sh
Your array n
should be declared as:
您的数组n
应声明为:
char[] n = new char[str.length()];
That creates an array with the exact size needed to put all your String
's characters in it.
这将创建一个数组,其大小与将所有String
's 字符放入其中所需的大小完全相同。
An ArrayIndexOutOfBoundsException
is thrown when you access an illegal index of the array, in this case I suspect your array is smaller than the length of the String
.
ArrayIndexOutOfBoundsException
当您访问数组的非法索引时会抛出An ,在这种情况下,我怀疑您的数组小于String
.
回答by Thomas
No need to create and fill such an array manually, there is a built-in method String.toCharArray
that does the job for you:
无需手动创建和填充这样的数组,有一个内置方法String.toCharArray
可以为您完成这项工作:
n = str.toCharArray()
回答by swapnil
If you want to convert string into character array then string class already have method called toCharArray().
如果你想将字符串转换为字符数组,那么字符串类已经有一个名为 toCharArray() 的方法。
String str = "StackOverflow";
char[] charArray = str.toCharArray();
then if you want to check content of array print it.
然后如果你想检查数组的内容打印它。
for(int i = 0;i < charArray.length ; i++) {
System.out.print(" " + charArray[i]);
}