Java an unremoveable white space string

僤鯓⒐⒋嵵緔 提交于 2019-12-25 02:48:14

问题


I have this string from mysql DB: it should be this: 2100428169/2010

this is my code

String str = rs.getString("str");
str = str.replaceAll("\\s+","");
str = str.trim();

char[] strCH = str.toCharArray();

and I get this:

[, 2, 1, 0, 0, 4, 2, 8, 1, 6, 9, /, 2, 0, 1, 0]

Why?

It's a problem because I need to use str1.equals(str) but it doesn't work because after

Object obj = (object)str;

It is in obj again with a space at the beginning like when I use toCharArray so it means equals doesn't work.


回答1:


I finally found solution:

it was problem because of ASCII 65279 is something from BOM and trim() doesn't work for it.

this helped: str = str.replace("\uFEFF", "");




回答2:


Neither replaceAll() nor trim() will work for some characters.
Actually there are several characters that could not be removed with this method. I even saw some files having characters that could not be recognized by java compiler, which creates unbelievable situations.
trim() method removes all \s from ends of string and by replaceAll() you are removing all \s from your string.
Instead use following

str = str.replaceAll("[^\\w\\\\]+", "");

You don't need to call trim() now.



来源:https://stackoverflow.com/questions/31038672/java-an-unremoveable-white-space-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!