problem with splitting a string
Hi, I am reading from a text file and trying to split the text i read on new line basis but it's not working, the whole file gets stored in 1 array element.
any ideas?
i tried string.split(" ") with \\n, \n, \r\n and they r all not working
//the code i use for splitting
publicvoid tokenize(String stringRead)
{
String[] tokenized = stringRead.split("\n");
int i = 0;
int x=0;
System.out.println("Tokenized = "+ tokenized.length);
for (int j=0; j < tokenized.length; j++)
System.out.println (tokenized[j]);
}
[929 byte] By [
zifoooa] at [2007-11-26 17:36:23]

Why don't you read the file using BufferedReader and its' readline method (I believe FileReader has this also). Then you don't have to worry about splitting it, as it will already be "split".
Edit: If you insist on using split then try with "\\n" instead of "\n", as you have to "escape" the escape character (\).
> Edit: If you insist on using split then try with
> "\\n" instead of "\n", as you have to "escape" the
> escape character (\).
No, not in the regexp.
public class Test {
public static void main(String[] args) {
String sampleData = "foo\nbar";
System.out.println(sampleData.split("\n").length);
}
}
Prints: 2
Kaj
> > Edit: If you insist on using split then try with
> > "\\n" instead of "\n", as you have to "escape" the
> > escape character (\).
>
> No, not in the regexp.
>
> > public class Test {
> public static void main(String[] args) {
> String sampleData = "foo\nbar";
> System.out.println(sampleData.split("\n").length);
> }
> }
>
>
> Prints: 2
>
> Kaj
Seemingly, they both work, but I will continue to use the double, as that is the way I learned it, and for many constructs it is needed (such as "\\s" will throw an error as "\s") so I find it much more consistent to use the double in all such situations.
If you are using readLine, then the file is being read line by line. So, each string you get is one line. If you are then mashing these lines onto a single String, that's your own fault. Save them in ana array, or ArrayList, or something, rather than saving the entire file in a single String.