2013-03-29 80 views
1

有一個字符串「早上好」。我想刪除字符串開始處的邊距(可能不是空格,它可能是換行符),並保留邊距的中間和後部。 如何做到這一點?如何去除字符串前面的空白?

+0

其中顯示該字符串?即TextView? EditText上? – danielcooperxyz

+0

修剪你的字符串! – hasanghaforian

+1

使用正則表達式。請參閱以下內容:http://www.vogella.com/articles/JavaRegularExpressions/article.html和http://docs.oracle.com/javase/tutorial/essential/regex/ – Luis

回答

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); 
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); 
+0

這不回答提出的問題。 –

+0

但它非常接近! –

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 ")); 
} 
相關問題