Full code (did not compileuntested)
Full code (did not compile)
Full code (untested)
Alternative to your code (another method, did not compile)
A simpler and faster alternative (besides what was mentioned before) is to perform a comparison through the whole of both strings but just ignoring any carriage return by skipping them, a carriage return by itself never represents a new line.
Explanations in comments:
public static StringUtils {
static final char CR = '\r';
/**
* Compares two strings ignoring any carriage return characters.
*/
public static boolean equalsIgnoringNewlineStyle(String a, String b) {
if (a == b) { // if both null return true
return true;
}
if (a == null || b == null) { // darn nulls
return false;
}
// each string's indices
int index_a = 0;
int index_b = 0;
// stop looping if we reach the end of either of the strings
while (index_a < a.length() && index_b < b.length()) {
// get each character
char first = a.charAt(index_a);
char second = b.charAt(index_b);
// if the same just continue
if (first == second) {
continue;
}
// if not a character we want to ignore, then the strings are not equal
if (first != CR && second != CR) {
return false;
}
// keep 'a_index' if 'second' is 'CR', otherwise go to next char
a_index = (second == CR ? a_index : a_index + 1);
// keep 'b_index' if 'first' is 'CR', otherwise go to next char
b_index = (first == CR ? b_index : b_index + 1);
}
// strings are equal if we went all the way through to the end of them
return index_a == a.length() && index_b == b.length();
}
}
Alternative to your code (another method, did not compile)
A simpler and faster alternative (besides what was mentioned before) is to perform a comparison through the whole of both strings but just ignoring any carriage return by skipping them, a carriage return by itself never represents a new line.
Explanations in comments:
public static StringUtils {
static final char CR = '\r';
/**
* Compares two strings ignoring any carriage return characters.
*/
public static boolean equalsIgnoringNewlineStyle(String a, String b) {
if (a == b) { // if both null return true
return true;
}
if (a == null || b == null) { // darn nulls
return false;
}
// each string's indices
int index_a = 0;
int index_b = 0;
// stop looping if we reach the end of either of the strings
while (index_a < a.length() && index_b < b.length()) {
// get each character
char first = a.charAt(index_a);
char second = b.charAt(index_b);
// if the same just continue
if (first == second) {
continue;
}
// if not a character we want to ignore, then the strings are not equal
if (first != CR && second != CR) {
return false;
}
// keep 'a_index' if 'second' is 'CR', otherwise go to next char
a_index = (second == CR ? a_index : a_index + 1);
// keep 'b_index' if 'first' is 'CR', otherwise go to next char
b_index = (first == CR ? b_index : b_index + 1);
}
// strings are equal if we went all the way through to the end of them
return index_a == a.length() && index_b == b.length();
}
}