0

Am Fetching few lines from remote server and saving each line as an arraylist element by setting dot as a separator. Everything works fine. I just don't understand why a strange rn value gets appended to every new line.

E.g.:

I am going to School. I am feeling hungry

gets split and displayed as

I am going to School

rnI am feeling hungry

What does that rn stands for?

I am using String.split to separate. My code is below.

List<String> po= new ArrayList<String>();

separated_q = Arrays.asList(prdesc.split(Pattern.quote(".")));

for(int k=0;k<separated_q.size();k++) {
    po.add(separated_q.get(k));
}

Please help me point out where am wrong.

Community
  • 1
  • 1
user3225075
  • 343
  • 1
  • 3
  • 22

2 Answers2

1

Remember, you are only splitting on the period, so if your text is:

I am going to School.
I am feeling hungry

the program sees this (especially on Windows):

I am going to School.\r\nI am feeling hungry

The \r is the carriage return character 0x0D and the \n is the linefeed character 0x0A. The split() isn't going to change anything with those characters, so you end up with

string[0] = "I am going to School"
string[1] = "\r\nI am feeling hungry"

You should probably be splitting on the line break itself, rather that the period. To do that, you would code this:

separated_q = Arrays.asList(prdesc.split("\\r?\\n"));

That should also get rid of the "\r\n" you are seeing.

See Split Java String by New Line

Community
  • 1
  • 1
kris larson
  • 28,608
  • 5
  • 53
  • 67
  • can you please edit my codes as per your suggestion coz by using trim nothing seems to change. still rn gets displayed – user3225075 Mar 29 '15 at 22:40
  • Let's back up a little bit. "Saving each line by adding the dot as a separator"... How are you doing that? You should just be able to split on the newline so you don't need to add the dot. See this answer: http://stackoverflow.com/questions/454908/split-java-string-by-new-line – kris larson Mar 30 '15 at 00:17
  • po.add(separated_q.get(k)); is how I save each line – user3225075 Mar 30 '15 at 09:19
  • I'm talking about the step even before that. This is data coming from a server, so you must have some code that reads the server data. Also I have concerns about splitting on the period, because by definition a line is a set of characters between linefeeds, or between a linefeed and the beginning/end of the document. What happens if there's a dot in the middle of the line? – kris larson Mar 30 '15 at 12:47
0
String myString = "I love writing code. It is so much fun!";

String[] split = myString.split(".");

String sentenceOne = split[0];
String sentenceTwo = split[1];
jb15613
  • 357
  • 3
  • 12
  • No, it's not going to display anything. But I can guarantee the values of sentenceOne and sentenceTwo Are the two sentences. Its up to you to display them. – jb15613 Mar 30 '15 at 03:22