Reputation: 6543
I'm trying to find a nice way to compare two strings when reading line by line in parallel. The reason i want to do that without using equals method or such is because the strings are not exactly the same, to be more accurate i'll give an example.
String s1 = "aaa\nbbb\nccc\ddd"
String s2 = "aaa\n\rbbb\n\rccc\n\rddd"
As u can see both strings has same values when we are looking line by line (though are not completly equal since s2 has also \r in it). Now, i know i can use some remove method to clean that "\r" but since the string can be very large, i prefer looping row by row and once the strings are not equal to break my logic. In other words i prefer iterating only the needed rows instead of cleanning the entrie string from \r.
edited: i am not reading from a file. these are plain strings.
Any ideas :) ?
Upvotes: 1
Views: 6383
Reputation: 68907
Since you said the string can be very large, I guess you are reading from a file. When you use a BufferedReader and use the readLine();
method, you will get line by line, without line separators. Now, you can use equals()
.
BufferedReader reader1 = ...; // depends on your source
BufferedReader reader2 = ...; // depends on your source
String line1 = null;
String line2 = null;
while ((line1 = reader1.readLine()) != null && (line2 = reader2.readLine()) != null)
{
if (line1.equals(line2))
{
}
}
Upvotes: 5
Reputation: 944
You can create two BufferedReader objects, one for each string and read line by line and compare the strings representing a line. The BufferedReader.readLine() method automatically strips the end of line chars (they are not added to the returned string).
BufferedReader br1 = new BufferedReader(new StringReader(s1)); is how you get the buffered reader created.
Upvotes: 2