Java an unremoveable white space string

2019-09-02 06:56发布

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.

2条回答
三岁会撩人
2楼-- · 2019-09-02 07:34

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.

查看更多
该账号已被封号
3楼-- · 2019-09-02 07:37

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", "");

查看更多
登录 后发表回答