Trimming text - when a lot of spaces is entered in the input field

I have an edit text box where I can enter a reason. But if a person enters all the spaces in the reason, how can I find him. Is there a way when a person goes into all the spaces or nothing, I have to save the text in the text as a simple "hiphen". My main question is how to trim these spaces at the end.

+4
source share
2 answers

The trim () method in String truncates extra spaces in strings.

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

str2 will equal Hello.

Regarding detection, when a person enters into all spaces - check str.length () after running str.trim ().

+12
source

You will also handle some events.

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

For your need there is a function:

 String String.trim(); 

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

to use it do the following:

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

now "msg" will have a "hyphen" if the user has not added anything.

it's almost what @Laurence said ..

+2
source

All Articles