-1

I'm working on a Registration UI and it checks if the user already exists in the database, the program works fine and all, but i have received bug reports that if you add whitespace at the start or end of the name you entered, it will assume its a new name and won't be blocked by detecting that the name already exists.

String name = txfUName.getText();

If(this.checkIfNameExists(name) == true);
{

...

}
else
{

...

}

How would I check if the first and last character is a whitespace (in a loop) and replace that whitespace with an empty string "" until there are no whitespaces in front or at the back of the name, assume the name can contain whitespaces in between words.

henriquehbr
  • 1,063
  • 4
  • 20
  • 41
dewald
  • 11
  • 2

2 Answers2

0

Please use string trim function

String name = txfUName.getText();

name = name.trim();

If(this.checkIfNameExists(name) == true); {

...

} else {

...

}
Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39
0

A very easy standard Java method from String - trim(). It removes leading and trailing white-space characters.

String name = txfUName.getText();
name = name.trim();

Or simply:

String name = txfUName.getText().trim();

Also, make sure getText() doesn't return null. If it does - implement a null check before calling trim().

Vaidas
  • 1,494
  • 14
  • 21