1

有一个字符串“早上好”。我想删除字符串开头的边距(可能不是空格,可能是换行)并保留边距的中间和后面。这该怎么做?

4

3 回答 3

1

trim()删除前导空格尾随空格时,要仅删除前导空格,您需要实现自己的 ltrim 方法,如下所示:

public static String ltrim(String s) {
    int i = 0;
    while (i < s.length() && Character.isWhitespace(s.charAt(i))) {
        i++;
    }
    return s.substring(i);
}

String myString = " whitespace be gone!";
String trimmedString = ltrim( myString );
于 2013-03-29T02:29:20.600 回答
1

正则表达式在这里可以很好地工作。当一个或多个空白字符 (\\s+) 出现在短语 (^) 的开头时,将这些前导空白字符替换为空字符串。

private static String trimLeading(String value) {
    return value != null ? value.replaceFirst("^\\s+", "") : null;
}

使用 JUnit/hamcrest 进行测试:

@Test
public void test() {
    assertThat(trimLeading("good morning "), is("good morning "));
    assertThat(trimLeading(" good morning "), is("good morning "));
    assertThat(trimLeading("  good morning "), is("good morning "));
    assertThat(trimLeading("\ngood morning "), is("good morning "));
    assertThat(trimLeading("\rgood morning "), is("good morning "));
    assertThat(trimLeading("\tgood morning "), is("good morning "));
    assertThat(trimLeading(" \t \n \r  good morning "), is("good morning "));
}
于 2013-03-29T08:04:13.813 回答
0
String b=" This is for test "
for(int i=0;i<=b.length()-1;i++)  
    {  
     char temp=b.charAt(i);  
     if(temp==' ')  
     {  
      whitespaceNumber++;  
     }  
    }  
    System.out.println("Whitespace number is : "+whitespaceNumber);  
于 2013-03-29T03:41:17.507 回答