Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 736
Tanz Avatar asked Aug 08 '26 22:08

Tanz


1 Answers

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.

like image 144
f1sh Avatar answered Aug 11 '26 10:08

f1sh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!