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

亡梦爱人 提交于 2019-12-10 16:47:32

问题


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.


回答1:


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().




回答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:

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



来源:https://stackoverflow.com/questions/4398360/trim-text-when-lot-of-space-keys-are-entered-at-end

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!