我有一个字符串,其开头有多个空格。
String str = " new york city";
我只希望删除第一个字符前的空格,以便replaceAll不起作用。
我有这行代码
if (str.startsWith(" ")){
str = str.replaceFirst(" ", ""); }
删除空格但不是全部空格。所以我需要执行此行直到
!str=startswith(" "))
我认为这可以通过循环实现,但我对循环非常不熟悉。我怎么能这样做?
提前谢谢。
答案 0 :(得分:2)
您也可以使用:
s.replaceAll("^\\s+", ""); // will match and replace leading white space
答案 1 :(得分:2)
答案 2 :(得分:0)
你可以这样做:
//str before trim = " new your city"
str = str.trim();
//str after = "new york city"
答案 3 :(得分:0)
您可以将if
更改为while
:
while (str.startsWith(" ")){
str = str.replaceFirst(" ", "");
另一个选择是使用Guava的CharMatcher
,它只支持修剪开头或仅支持结束。
str = CharMatcher.is( ' ' ).trimLeadingFrom( str );
答案 4 :(得分:0)
使用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);
}
答案 5 :(得分:0)
快速的Google搜索带来了一个页面,其中简单概述了两个基本循环,同时执行:
http://www.homeandlearn.co.uk/java/while_loops.html
在您的情况下,您希望使用“while”类型的循环,因为您想在进入循环之前检查条件。所以它看起来像这样:
while (str.startsWith(" ")){
str = str.replaceFirst(" ", "");
}
您应该确保使用类似“”(仅为空格)和“”(空字符串)的字符串来测试此代码,因为当输入字符串为空时,我不完全确定startsWith()的行为方式。
学习循环将是非常必要的 - 至少,如果你的计划涉及的不仅仅是通过一个你并不真正想要的编程课程。 (如果你认为“while”循环很复杂,那么等到你遇到“for”!)