你可以尝试这样的事情:
/**
* Remove white spaces from string according to mode
*
* @param str string
* @param mode mode 0=leading, 1=trailing, 2=leading+trailing
* @param result - result buffer
* @return number of white spaces removed
*/
public int removeWhiteSpacesByMode(String str, int mode, StringBuilder result) {
int n = 0;
switch(mode) {
case 0:
n = removeLeadingWhiteSpaces(str, result);
break;
case 1:
n = removeTrailingWhiteSpaces(str, result);
break;
case 2:
StringBuilder tmp = new StringBuilder();
n = removeTrailingWhiteSpaces(str, tmp);
n += removeLeadingWhiteSpaces(tmp.toString(), result);
break;
default:
throw new IllegalArgumentException("mode=" + mode);
}
return n;
}
private int removeTrailingWhiteSpaces(String str, StringBuilder result) {
int n = 0;
if(str != null && result != null) {
n = str.length()-1;
while(Character.isWhitespace(str.charAt(n))) {
n--;
}
n++;
for(int j = 0; j < n; j++) {
result.append(str.charAt(j));
}
n = str.length() - n;
}
return n;
}
private int removeLeadingWhiteSpaces(String str, StringBuilder result) {
int n = 0;
if(str != null && result != null) {
while(Character.isWhitespace(str.charAt(n))) {
n++;
}
for(int j = n; j < str.length(); j++) {
result.append(str.charAt(j));
}
}
return n;
}
它使用Character#isWhitespace方法来检查字符是否为空格,并使用StringBuilder来构建结果。返回值是删除的白色步数。
如果你想有一个方法来计算字符串中的空格,你可以遍历整个字符串,使用Character#isWhitespace检查每个字符,如果它返回 true,则增加一个变量。
最后是一些测试:
@Test
public void removeWhiteSpacesByMode() {
String str = " home sweet home ";
StringBuilder result = null;
int numberOfWhiteSpacesRemoved = 0;
numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(str, 0, null);
Assert.assertEquals(numberOfWhiteSpacesRemoved, 0);
result = new StringBuilder();
numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(null, 0, result);
Assert.assertEquals(0, result.length());
Assert.assertEquals(numberOfWhiteSpacesRemoved, 0);
try {
result = new StringBuilder();
numberOfWhiteSpacesRemoved = 0;
numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(null, 4, result);
Assert.fail("mode 4 should not have been accepted");
} catch(IllegalArgumentException e) {
Assert.assertEquals("mode=4", e.getMessage());
Assert.assertEquals(0, result.length());
Assert.assertEquals(numberOfWhiteSpacesRemoved, 0);
}
result = new StringBuilder();
numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(str, 0, result);
Assert.assertEquals("home sweet home ", result.toString());
Assert.assertEquals(numberOfWhiteSpacesRemoved, 1);
result = new StringBuilder();
numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(str, 1, result);
Assert.assertEquals(" home sweet home", result.toString());
Assert.assertEquals(numberOfWhiteSpacesRemoved, 2);
result = new StringBuilder();
numberOfWhiteSpacesRemoved = removeWhiteSpacesByMode(str, 2, result);
Assert.assertEquals("home sweet home", result.toString());
Assert.assertEquals(numberOfWhiteSpacesRemoved, 3);
}