always meet problem with java string's last end of string sign. It seems it occupy a space, therefore it may be return different answers when do if string[a] == string[b], or even sometimes a.equals(b) still doesn't work even a and b seems the same but one of them contain a end sign. Wonder Which function can be used for the ignoring feature of the string?
Asked
Active
Viewed 771 times
-10
-
2You could try trimming the whitespace with `.trim()` – Blender Apr 15 '13 at 07:30
-
1`String#trim`, `String#startsWith`...? – MadProgrammer Apr 15 '13 at 07:30
-
3`string[a] == string[b]` don't do that – Thilo Apr 15 '13 at 07:31
-
1first trim the string then compare using equals , here == won't work – Senthil Apr 15 '13 at 07:31
-
2Why did you tag this with C++? – Rapptz Apr 15 '13 at 07:32
-
Do you have the same problem with C++'s string? – juanchopanza Apr 15 '13 at 07:33
-
Rapprz I think C++ may count the same question so I tagged it. (I know now normally in C++ people always use char array instead of string) @juanchopanza yes, I did have the same problem with C++ before. – Lance Apr 18 '13 at 15:55
4 Answers
4
Use String.trim()
to remove surrounding whitespace and then use String.equals()
(not ==
, See 15.21 Equality Operators in the Java Language Specification for full details.). Remember that String
instances are immutable so String.trim()
returns a new String
and it is that which must be used in the equals()
check.
Note that trim()
removes leading whitespace also. If this is undesired then use String.substring()
to erase the trailing whitespace.

hmjd
- 120,187
- 20
- 207
- 252
0
trim()
will return your string without spaces in the start and ends.
Ex:
String s =" test ";
s =s.trim(); //will become "test"

Suresh Atta
- 120,458
- 37
- 198
- 307