简体   繁体   English

在 Java 中,删除字符串的第一个字符,如果它是 ,(逗号)

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

In Java, I have a String variable.在 Java 中,我有一个 String 变量。

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?做到这一点的最佳方法是什么?

Something like:就像是:

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

is pretty simple...很简单...

我会将^锚与replaceFirst()一起使用:

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

如果您的类路径中有 commons-lang,可以查看StringUtils.removeStart(String str, String remove)

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;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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