Search code examples
javaarrayssubstring

Substring into an array in Java


I'm wanting to store an a substring into a new array.

Here is my substring data = line.substring(i, i+1);

How do i do this? I have tried String data [] = line.substring(i, i+1) but not worked.

Thanks


Solution

  • .substring() does not return an array, it returns a String so passing it into an array won't work. You can split a String into a String[] array using the .split(String regex) method. The paramter is the delimiting regular expression, meaning if you did "Hello World".split(" "); (with space as the argument), the resulting array would be ["Hello", "World"]. If you want to split all of the characters into their own index of the array, just pass in an empty String "" as the argument of the split method (like line.split("")).

    If your goal is to store the String in an array you can pass it in with a regular array declaration and assignment: String[] data = { line.substring(i, i + 1) }; or just make a new array and pass it into the desired index.