Reputation: 386
I'm trying to split the individual elements of a String[]
array. The array looks like
{"0 1 0 1", "0 0 1 1", "1 1 0 1",...}.
I want to split each element by the regex " ", a single space. If I do that, does it make the one element "0 1 0 1" into 4 elements "0", "1", "0", and "1"? Here is my code that adds the elements to the list (reading from a text file with rows of 4 digit numbers separated by spaces) but the part using the "split" method is not working. It is not having any affect on the array produced. The name of the String[]
array is "splitted".
int j=0;
String thisLine = null;
while(((thisLine=readThrough.readLine()) != null) && j<3){
splitted[j]= thisLine;
splitted[j].split(" ");
j++;
}
Upvotes: 3
Views: 17319
Reputation: 235984
The split()
method doesn't modify the string in-place, you have to assign the returned String[]
to something. If you want to process all the values, try something like this:
String[] array = {"0 1 0 1", "0 0 1 1", "1 1 0 1"};
List<String> answer = new ArrayList<String>();
for (String str : array)
for (String s : str.split(" "))
answer.add(s);
After the loop runs, answer
will contain the following string values:
[0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1]
Optionally, if you need the output result as an array of strings you can do this:
String[] output = answer.toArray(new String[answer.size()]);
Upvotes: 4
Reputation: 324098
splitted[j].split(" ");
This method returns an Array contain the 4 values. You didn't assign the result of the split() method to any variable.
In any case you can't just add 4 values to an single Array index (which is what it looks like you are trying to do).
You would need code something like:
String[] values = thisLine.split(" " );
for (int i = 0; i < values.length; i++)
splitted[j++] = values[i];
Of course don't forget to make your Array large enough to hove all the values. The size will need to be 4 x rows of data.
Upvotes: 0