Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim text- when lot of space keys are entered at end

Tags:

java

android

trim

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 nothing , i have to save the text the text as a simple "hiphen". My main question is how to trim those spaces coming at the end.

like image 475
xydev Avatar asked Dec 09 '22 12:12

xydev


2 Answers

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

String str = "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().

like image 181
Joakim Berglund Avatar answered Dec 22 '22 09:12

Joakim Berglund


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:

String String.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..

like image 26
Aman Alam Avatar answered Dec 22 '22 09:12

Aman Alam