joe dacoolguy
joe dacoolguy

Reputation: 309

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.

Upvotes: 1

Views: 128

Answers (6)

arshajii
arshajii

Reputation: 129572

replaceFirst takes a regular expression, so you want

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

Simple as pie.

Upvotes: 2

RobertB
RobertB

Reputation: 1076

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"!)

Upvotes: 0

Vikas V
Vikas V

Reputation: 3196

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

Upvotes: 0

Andy Thomas
Andy Thomas

Reputation: 86509

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

Upvotes: 0

jh314
jh314

Reputation: 27812

You can also use this:

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

Upvotes: 2

SOfanatic
SOfanatic

Reputation: 5573

You could do:

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

Upvotes: 0

Related Questions