如何删除字符串前面的空白?

时间:2013-03-29 02:25:53

标签: android

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

3 个答案:

答案 0 :(得分: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 );

答案 1 :(得分: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 "));
}

答案 2 :(得分: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);