Reputation: 225
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
Reputation: 385
If you have commons-lang in your classpath, may have a look at StringUtils.removeStart(String str, String remove)
Upvotes: 2
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
Reputation: 46209
I would use the ^
anchor together with replaceFirst()
:
niceString = yourString.replaceFirst("^,", "");
Upvotes: 20
Reputation: 1500145
Something like:
text = text.startsWith(",") ? text.substring(1) : text;
is pretty simple...
Upvotes: 49