Reputation: 197
I have some basic code that is supposed to format an input string. The input string has a list of words, separated with a newline. My code is supposed to add to add a few chars to the beginning and end of each line. ("\"-" in the beginning and "\"," in the end.) However, although each element in the list is printed correctly when printing separately, the var 'out' does not contain all the elements, instead it contains "\",\"".
String[] split = everything.split("\n");
String out = "\"";
for (String split1 : split) {
System.out.println(split1);
out = out + "-" + split1.toLowerCase() + "\",\"";
}
System.out.println(out);
For example, for the input string:
Indonesian\nid\nYiddish\nyi
prints:
Indonesian
id
Yiddish
yi
","
when it should print:
Indonesian
id
Yiddish
yi
"-indonesian","-id","-yiddish","-yi","
Can someone explain what is causing this behavior and how to fix it?
Update:
I did some more testing. It seems if i simply set everything
to Indonesian\nid\nYiddish\nyi
then the desired output comes out. However, everything
is read from a big text file. I pasted the contents of the file here: http://pastebin.com/Tjf9dzcb
I read the file like this:
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\xxxx\\Desktop\\hi.txt"));
String everything = null;
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
everything = sb.toString();
} finally {
br.close();
}
Upvotes: 2
Views: 126
Reputation: 5741
Use both sb.append();
and everything.split()
with same parameter.
sb.append("\n");
String[] split = everything.split("\n");
Or
sb.append(System.lineSeparator());
String[] split = everything.split(System.lineSeparator());
EDIT
Definition of System.lineSeparator()
in JavaDoc
Returns the system-dependent line separator string. It always returns the same value - the initial value of the system property line.separator. On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".
So if your system is Windows then System.lineSeparator()
is equivalent to "\r\n"
. In UNIX your previous code should work well.
Upvotes: 3