为什么修剪不起作用?

Rac*_*hel 20 java

我试图修剪字符串中的前导空格,我不知道我的方法有什么问题,任何建议都会受到赞赏吗?

码:

this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();

我正在从csv文件中读取poNumber为"IG078565和IG083060",并且输出也是相同的空格相同的值,不知道为什么?

更新

为更好的上下文添加完整方法:

public BillingDTO(String currency, String migrationId, String chargeId, String priceId, String poNumber, String otc,
            String billingClassId, String laborOnly) {
        super();
        this.currency = currency.equals("") ? currency : currency.trim();
        this.migrationId = migrationId.equals("") ? migrationId : migrationId.trim();
        this.chargeId = chargeId.equals("") ? chargeId : chargeId.trim();
        this.priceId = priceId.equals("") ? priceId : priceId.trim();
        this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();
            //poNumber.trim();
        //System.out.println("poNumber:"+this.poNumber.trim());
        //this.poNumber = poNumber.equals("") ? poNumber : poNumber.trim();
        this.otc = otc.equals("") ? otc : otc.trim();
        this.billingClassId = billingClassId.equals("") ? billingClassId : billingClassId.trim();
        this.laborOnly = laborOnly.equals("") ? "N" : laborOnly;
    }
Run Code Online (Sandbox Code Playgroud)

谢谢.

Boz*_*zho 47

更新看起来你的空格不是空格(ascii = 32).你的代码是160,这是一个不间断的空间.trim()不处理它.所以你必须做这样的事情:

this.poNumber = poNumber.replace(String.valueOf((char) 160), " ").trim();
Run Code Online (Sandbox Code Playgroud)

你最好创建一个实用程序 - YourStringUtils.trim(string)并执行两个操作 - 两者.trim()replace(..)


原始答案:

只是用 this.poNumber = poNumber.trim();

如果有一个可能性poNumbernull,那么你可以使用空安全this.poNumber = StringUtils.trim(poNumber);公共浪.

trimToEmpty(..)如果要将null其转换为空字符串,也可以在同一个类中使用.

如果你不想依赖commons-lang,那么只需添加一个if子句:

if (poNumber != null) {
    this.poNumber = poNumber.trim();
}
Run Code Online (Sandbox Code Playgroud)

正如问题中的评论中所述 - 确保在修剪后检查正确的变量.您应该检查实例变量.你的参数(或局部变量,我无法分辨)不会改变,因为字符串是不可变的.

  • `replace((char)160,'')`可以代替使用. (3认同)
  • 很棒的答案Bozho,这节省了我的培根!就像一个小调整,我建议使用`replace(String.valueOf((char)160),"");`而不是`replace(String.valueOf((char)160),"");`(即,用真实空间替换非破坏空间,trim()可以删除).这样,如果在字符串中间有其他不间断的空格你正在修剪它们将被普通空格而不是空格所取代. (2认同)