-2

It may look a Stupid question, but It is giving wrong output !!

The trim() is supposed to delete the 'space' or 'new line' character at the beginning or end of the String, but it isn't working.

String str=str.getText().toString();
str.trim();
if(str.equalsIgnoreCase("STRING"))
    mytextview.setText("True");
else
    mytextview.setText("False");

If I'm Entering ---> " STRING " (With many spaces ), I am getting False as the Answer .... I'm using Eclipse Juno for my Androing Project, are there any exceptions ? Please Help.

Vaido
  • 111
  • 1
  • 7

5 Answers5

5
String str=str.getText().toString();
str.trim();

should be:

String str=str.getText().toString();
str = str.trim();

Strings are immutable in Java. An operation like trim() creates a new String.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
kosa
  • 65,990
  • 13
  • 130
  • 167
  • @user2525485: Looks like Nambari beat all of us to the answer. The best way for this site to help others is select an answer. That way if others view the question they have a clear "correct" answer. You can mark the selected answer by clicking on the checkmark next to Nambari's answer. – Vanquish46 Jul 01 '13 at 17:58
2

You are not storing the output of str.trim(). It does not modify the original String; rather, it generates a new, separate one.

You can store it back into the original by using str = str.trim().

asteri
  • 11,402
  • 13
  • 60
  • 84
1

String.trim() returns the resulting trimmed string.

You need to do str = str.trim();

Vanquish46
  • 494
  • 1
  • 5
  • 15
1

The trim method returns a copy of the string. Change the second line to be:

str = str.trim();

Source: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim()

Olivia
  • 36
  • 1
1

Use

 String str=str.getText().toString().trim();
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115