Skip to content Skip to sidebar Skip to footer

Trim Text- When Lot Of Space Keys Are Entered At End

I have a edit text field in which reason can be entered. But if a person enters all spaces in the reason how can I detect it. Is there a way when a person enters all spaces or noth

Solution 1:

The method trim() in String trims excess spaces on Strings.

Stringstr = "Hello  ";
String str2 = str.trim();

str2 would equal "Hello".

As for detecting when a person enters all spaces - check the str.length() after you've ran str.trim().

Solution 2:

You would be handling some events too..

like whenever the user clicks a button, you collect the text of your edit text.

For your need, there's a function:

StringString.trim();

it removes all the spaces that are before and after your text (leading and trailing spaces)

to use it, do this:

String msg = editText.getText().toString();
msg = msg.trim();
if(msg.equals("")){
  msg = "-";
}

now 'msg' will be having a 'hyphen' in case user has entered nothing.

this is almost what @Laurence said..

Post a Comment for "Trim Text- When Lot Of Space Keys Are Entered At End"