为什么修剪不起作用?

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

码:

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

谢谢。

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

 this.poNumber = poNumber.replace(String.valueOf((char) 160), " ").trim(); 

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


原始答案:

只需使用this.poNumber = poNumber.trim();

如果poNumber有可能为null ,那么你可以使用null-safe this.poNumber = StringUtils.trim(poNumber); 来自commons-lang 。

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

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

 if (poNumber != null) { this.poNumber = poNumber.trim(); } 

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

你确定你正在为输出读取正确的变量吗? 你有’poNumber’,它是原始的未修剪字符串,’this.poNumber’,它将获得修剪后的字符串。

您的文件可能具有未被修剪的非ascii空格。 例如,有一个unicode字符不间断空格(U + 00A0),它显示为空格但不被trim修剪(这可能是您在wordpad或其他编辑器中编辑的文档中看到的,这些文档试图“帮助” “你。”如果查看String.trim()的定义,它会删除<=''的字符(即小于或等于20的值)。

因此,打印字符串的字节值(或在hex编辑器中查看)并确保您的空格实际上是空格(即十进制值20)。 如果您需要其他行为,您可能需要编写自己的trim实用程序函数,该函数使用正确的unicode Character.isWhiteSpace(char)检查。

你可以使用这个函数,我对java trim()方法做了一些操作,这比一些replace()方法更好,更快,更有效。

 public static String trimAdvanced(String value) { Objects.requireNonNull(value); int strLength = value.length(); int len = value.length(); int st = 0; char[] val = value.toCharArray(); if (strLength == 0) { return ""; } while ((st < len) && (val[st] <= ' ') || (val[st] == '\u00A0')) { st++; if (st == strLength) { break; } } while ((st < len) && (val[len - 1] <= ' ') || (val[len - 1] == '\u00A0')) { len--; if (len == 0) { break; } } return (st > len) ? "" : ((st > 0) || (len < strLength)) ? value.substring(st, len) : value; }