Reputation: 41
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
Upvotes: 3
Views: 22913
Reputation: 230
If you want to convert string into character array then string class already have method called 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]);
}
Upvotes: 2
Reputation: 17412
No need to create and fill such an array manually, there is a built-in method String.toCharArray
that does the job for you:
n = str.toCharArray()
Upvotes: 4
Reputation: 11934
Your array n
should be declared as:
char[] n = new char[str.length()];
That creates an array with the exact size needed to put all your String
's characters in it.
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
.
Upvotes: 5