-10

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?

Rapptz
  • 20,807
  • 5
  • 72
  • 86
Lance
  • 551
  • 4
  • 5

4 Answers4

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
1

should always trim() the string before compare.

Ankit
  • 6,554
  • 6
  • 49
  • 71
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
0

you can use only stringA.equals(stringB); to remove white spaces use .trim()

x3mik
  • 61
  • 1
  • 2
  • 5