Home > Back-end >  Auto remove ending space of any text of EditText
Auto remove ending space of any text of EditText

Time:05-31

Description

I am developing one app in which I have registration page. Inside registration page, I am doing registration by getting user's full name and mobile number.

Problem

While getting user's full name in edit text sometimes the user is pressing space bar after typing his/her name.

I don't need space in my database after typing any text white user.

CodePudding user response:

.trim() would remove whitespaces from the input, but you should probably then use two inputs, one for first name and one for last name

val string = "Bobby  "
val trimmed = string.trim()

Trimmed = "Bobby"

CodePudding user response:

not quite sure how your structure works, but if I understand the question correctly you just need a while loop going backwards from the end of the string checking to see if it is a space, if it is, remove it.

This assumes your input contains both first and last name, and only removes the whitespace at the end.

something like this should work:

Sting input = "input ";
while (input.charAt(input.length()-1) == ' '){
        input = input.substring(0, input.length()-1);
    }

CodePudding user response:

I would also recommend that you implement some kind of validations. For example, for an only whitespaces(spaces, tabs, new lines, etc...) input.

An example:

  1. Get the UI element, in which the user will type:

EditText firstName = requireActivity().findViewById(R.id.registerFirstName);

  1. Take the string value of the user's input and validate it as you wish:

String firstNameStr = firstName.getText().toString();

if (firstNameStr.trim().equals("")) { Make a Toast or something }

This way you are certain there are no extra whitespaces and the input is not empty.

CodePudding user response:

Use string.trim()

why to use trim()

The trim() method in Java String is a built-in function that eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.

  • Related