vinay
vinay

Reputation: 9

Comparing Strings with BREAK LINES in Java

I have two Strings as below:

String A = "Hello World";
String B = "Hello \n World";

The only difference between the Strings is a line break, my question is how can we compare these strings by ignoring the line breaks.

Upvotes: 0

Views: 927

Answers (2)

Oleg Cherednik
Oleg Cherednik

Reputation: 18255

I believe, that the following string should be equal: "Hello World" and "Hello \nWorld".

The simplest way is to remove \n from the both strings and then use isEquals():

public static boolean isEquals(String one, String two) {
    one = one.replace("\n", "");
    two = two.replace("\n", "");
    return one.equals(two);
}

But it could be not efficient because here we have additional string object creations. Fortunately, you could use another approach.

public static boolean isEquals(String one, String two) {
    int i = 0;
    int j = 0;

    while (i < one.length() && j < two.length()) {
        if (one.charAt(i) == '\n')
            i++;
        else if (two.charAt(j) == '\n')
            j++;
        else if (one.charAt(i++) != two.charAt(j++))
            return false;
    }

    for (; i < one.length(); j++)
        if (one.charAt(i) != '\n')
            return false;

    for (; j < two.length(); j++)
        if (two.charAt(j) != '\n')
            return false;

    return true;
}

Upvotes: 2

ShunnedJeans
ShunnedJeans

Reputation: 97

A.equals(B.replaceAll("\n","").replaceAll("  "," "));

String String.replaceAll(String regex, String replacement)

Replaces each substring of this string that matches the given regular expression with the given replacement.

boolean String.equals(Object anObject)

Compares this string to the specified object.The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object. For finer-grained String comparison, refer to java.text.Collator

Upvotes: 0

Related Questions