Tanz
Tanz

Reputation: 41

Java-Storing characters of a string in an array

    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

Answers (3)

swapnil
swapnil

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

Thomas
Thomas

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

f1sh
f1sh

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

Related Questions