1/*  Copyright (c) 2000-2006 hamcrest.org
2 */
3package org.hamcrest.text;
4
5import org.hamcrest.Description;
6import org.hamcrest.Matcher;
7import org.hamcrest.Factory;
8import org.hamcrest.TypeSafeMatcher;
9
10/**
11 * Tests if a string is equal to another string, ignoring any changes in whitespace.
12 */
13public class IsEqualIgnoringWhiteSpace extends TypeSafeMatcher<String> {
14
15    // TODO: Replace String with CharSequence to allow for easy interopability between
16    //       String, StringBuffer, StringBuilder, CharBuffer, etc (joe).
17
18    private final String string;
19
20    public IsEqualIgnoringWhiteSpace(String string) {
21        if (string == null) {
22            throw new IllegalArgumentException("Non-null value required by IsEqualIgnoringCase()");
23        }
24        this.string = string;
25    }
26
27    public boolean matchesSafely(String item) {
28        return stripSpace(string).equalsIgnoreCase(stripSpace(item));
29    }
30
31    public void describeTo(Description description) {
32        description.appendText("eqIgnoringWhiteSpace(")
33                .appendValue(string)
34                .appendText(")");
35    }
36
37    public String stripSpace(String string) {
38        StringBuilder result = new StringBuilder();
39        boolean lastWasSpace = true;
40        for (int i = 0; i < string.length(); i++) {
41            char c = string.charAt(i);
42            if (Character.isWhitespace(c)) {
43                if (!lastWasSpace) {
44                    result.append(' ');
45                }
46                lastWasSpace = true;
47            } else {
48                result.append(c);
49                lastWasSpace = false;
50            }
51        }
52        return result.toString().trim();
53    }
54
55    @Factory
56    public static Matcher<String> equalToIgnoringWhiteSpace(String string) {
57        return new IsEqualIgnoringWhiteSpace(string);
58    }
59
60}
61