[英]How to execute an if line more than once until a certain condition is met
我有一個字符串,其開頭有多個空格。
String str = " new york city";
我只想刪除第一個字符前的空格,因此replaceAll不起作用。
我有這行代碼
if (str.startsWith(" ")){
str = str.replaceFirst(" ", ""); }
這會刪除一個空格但不是全部。 所以我需要執行此行直到
!str=startswith(" "))
我認為這可以通過循環實現,但我對循環非常不熟悉。 我怎樣才能做到這一點?
先感謝您。
你也可以用這個:
s.replaceAll("^\\s+", ""); // will match and replace leading white space
你可以這樣做:
//str before trim = " new your city"
str = str.trim();
//str after = "new york city"
您可以將if
更改為while
:
while (str.startsWith(" ")){
str = str.replaceFirst(" ", "");
另一種選擇是使用Guava的CharMatcher
,它只支持修剪開始或僅支持結束。
str = CharMatcher.is( ' ' ).trimLeadingFrom( str );
使用trim()將刪除起始和結束空格。 但是,由於您要求刪除起始空格,因此下面的代碼可能有所幫助。
public String trimOnlyLeadingSpace()
{
int i = this.count;
int j = 0;
int k = this.offset;
char[] arrayOfChar = this.value;
while ((j < i) && (arrayOfChar[(k + j)] <= ' '))
++j;
return (((j > 0) || (i < this.count)) ? substring(j, i) : this);
}
一個快速的谷歌搜索帶來了一個頁面,簡單概述了兩個基本循環,同時和do-while:
http://www.homeandlearn.co.uk/java/while_loops.html
在您的情況下,您希望使用“while”類型的循環,因為您想在進入循環之前檢查條件。 所以它看起來像這樣:
while (str.startsWith(" ")){
str = str.replaceFirst(" ", "");
}
您應該確保使用類似“”(僅為空格)和“”(空字符串)的字符串來測試此代碼,因為當輸入字符串為空時,我不完全確定startsWith()的行為。
學習循環將是非常重要的 - 至少,如果你的計划涉及的不僅僅是通過一個你並不真正想要的編程課程。 (如果你認為“while”循環很復雜,那么等到你遇到“for”!)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.