Skip to content

Commit d619551

Browse files
committed
Simplifying CompressingWhiteSpace
1 parent ff1ab0b commit d619551

File tree

2 files changed

+5
-19
lines changed

2 files changed

+5
-19
lines changed

hamcrest-library/src/main/java/org/hamcrest/text/IsEqualCompressingWhiteSpace.java

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public IsEqualCompressingWhiteSpace(String string) {
2525

2626
@Override
2727
public boolean matchesSafely(String item) {
28-
return stripSpace(string).equals(stripSpace(item));
28+
return stripSpaces(string).equals(stripSpaces(item));
2929
}
3030

3131
@Override
@@ -40,22 +40,8 @@ public void describeTo(Description description) {
4040
.appendText(" compressing white space");
4141
}
4242

43-
public String stripSpace(String toBeStripped) {
44-
final StringBuilder result = new StringBuilder();
45-
boolean lastWasSpace = true;
46-
for (int i = 0; i < toBeStripped.length(); i++) {
47-
char c = toBeStripped.charAt(i);
48-
if (isWhitespace(c)) {
49-
if (!lastWasSpace) {
50-
result.append(' ');
51-
}
52-
lastWasSpace = true;
53-
} else {
54-
result.append(c);
55-
lastWasSpace = false;
56-
}
57-
}
58-
return result.toString().trim();
43+
public String stripSpaces(String toBeStripped) {
44+
return toBeStripped.replaceAll("\\s+", " ").trim();
5945
}
6046

6147
/**

hamcrest-library/src/test/java/org/hamcrest/text/IsEqualCompressingWhiteSpaceTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
public class IsEqualCompressingWhiteSpaceTest extends AbstractMatcherTest {
99

10-
private final Matcher<String> matcher = equalToCompressingWhiteSpace("Hello World how\n are we? ");
10+
private final Matcher<String> matcher = equalToCompressingWhiteSpace(" Hello World how\n are we? ");
1111

1212
@Override
1313
protected Matcher<?> createMatcher() {
@@ -38,7 +38,7 @@ public void testFailsIfMatchingAgainstNull() {
3838
}
3939

4040
public void testHasAReadableDescription() {
41-
assertDescription("a string equal to \"Hello World how\\n are we? \" compressing white space",
41+
assertDescription("a string equal to \" Hello World how\\n are we? \" compressing white space",
4242
matcher);
4343
}
4444
}

0 commit comments

Comments
 (0)