简体   繁体   中英

How to execute an if line more than once until a certain condition is met

I have a string that has multiple spaces in its beginning.

String str = "  new york city";

I want only the spaces before the first character to be deleted so a replaceAll would not work.

I have this line of code

 if (str.startsWith(" ")){
  str = str.replaceFirst(" ", "");          }

This deletes a space but not all. So I need this line to be executed until

!str=startswith(" "))

I think this can be achieved through a loop but I am VERY unfamiliar with loops. How can I do this?

Thank you in advance.

你也可以用这个:

s.replaceAll("^\\s+", ""); // will match and replace leading white space

replaceFirst takes a regular expression, so you want

str = str.replaceFirst("\\s+", "");

Simple as pie.

You could do:

//str before trim = "    new your city"
str = str.trim();
//str after = "new york city"

You could change the if to a while :

 while (str.startsWith(" ")){
    str = str.replaceFirst(" ", ""); 

Another option is to use Guava's CharMatcher , which supports trimming only the beginning, or only the end.

 str = CharMatcher.is( ' ' ).trimLeadingFrom( str );

Using trim() would remove both starting and ending spaces. But, since you are asking to remove starting spaces, below code might help.

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);
  }

A quick Google search brought up a page with a simple overview of the two basic loops, while and do-while:

http://www.homeandlearn.co.uk/java/while_loops.html

In your case, you want to use a "while" type of loop, because you want to check the condition before you enter the loop. So it would look something like this:

while (str.startsWith(" ")){
  str = str.replaceFirst(" ", "");
}

You should be sure to test this code with a string like " " (just a blank space) and "" (empty string), because I'm not entirely sure how startsWith() behaves when the input string is empty.

Learning loops is going to be pretty essential - at least, if your plans involve more than just get through a programming class that you didn't really want to take. (And if you think "while" loops are complicated, wait until you meet "for"!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM