srini
srini

Reputation: 225

In Java, remove the first char of the string if it is , (comma)

In Java, I have a String variable.

Sometimes the first character of the string is a comma ,

I want to remove the first char only if it is a comma.

What is the best approach to do this?

Upvotes: 15

Views: 36258

Answers (4)

ThiamTeck
ThiamTeck

Reputation: 385

If you have commons-lang in your classpath, may have a look at StringUtils.removeStart(String str, String remove)

Upvotes: 2

leonardo rey
leonardo rey

Reputation: 737

Try this

public String methodNoCharacter(String input, String character){

if(input!= null && input.trim().length() > 0)//exist
            if(input.startsWith(character))//if start with '_'
                return methodNoCharacter(input.substring(1));//recursive for sure!

        return input;

}

Upvotes: 0

Keppil
Keppil

Reputation: 46209

I would use the ^ anchor together with replaceFirst():

niceString = yourString.replaceFirst("^,", "");

Upvotes: 20

Jon Skeet
Jon Skeet

Reputation: 1500145

Something like:

text = text.startsWith(",") ? text.substring(1) : text;

is pretty simple...

Upvotes: 49

Related Questions