2015-02-09 56 views
1

我嘗試做一些這樣的:我怎麼能在一個字符串replce最後空間(在Java)

String result = "Most Trees Are Blue "; 

//Should be return a string without last space 

return result.replaseAll("REGEX", ""); 

結果必然是「大多數樹木藍」,我可以這樣做:

return new StringBuilder(result).deleteCharAt(result.length()-1).toString(); 

,但我想用正則表達式做。我該怎麼做?

+4

'字符串#TRIM()'? – 2015-02-09 01:16:27

+0

@SotiriosDelimanolis我認爲它也會去掉領先空間。 – 2015-02-09 01:21:11

+0

@AvinashRaj儘管如此,但OP的示例並不包含前導空格。 – 2015-02-09 01:24:18

回答

2

使用正則表達式,可以使用replaceAll("\\s+$", "")

String result = "Most Trees Are Blue "; 
result = result.replaceAll("\\s+$", ""); 
System.out.printf("'%s'%n", result); 

\\s+將匹配一個(或多個)的空白字符,所述$表示在String結束,然後將""是替換值。輸出是,

'Most Trees Are Blue' 

您也可以使用String.trim()

String result = "Most Trees Are Blue ".trim(); 
2

使用,你說會是正則表達式的方法...

String result = "Most Trees Are Blue ".replaceAll("\\s+$", ""); 
System.out.println(result); //=> "Most Trees Are Blue" 
相關問題