Reputation: 37
i have this code in my app. which accepts the value of the edittext
if (ans.equalsIgnoreCase("bag")) {
btnEnter.setEnabled(false);
int a=Integer.parseInt(textView2.getText().toString());
int b=a+10;
String s1 = String.valueOf(b);
textView2.setText(s1);
Toast.makeText(getApplicationContext(), "Correct",Toast.LENGTH_SHORT).show();
my problem is if the user puts a single space in the edittext then proceeds with the "bag" it still prompts wrong like this for example
" " = space
" " bag ----- wrong bag ----- correct
how can i set that with space it can accept
Upvotes: 0
Views: 378
Reputation: 44571
String ans2 = ans.trim();
if (ans2.equalsIgnoreCase("bag")) {
btnEnter.setEnabled(false);
int a=Integer.parseInt(textView2.getText().toString());
int b=a+10;
String s1 = String.valueOf(b);
textView2.setText(s1);
Toast.makeText(getApplicationContext(), "Correct",Toast.LENGTH_SHORT).show();
Returns a copy of the string, with leading and trailing whitespace omitted.
Since @ρяσѕρєя K deleted his answer before I got back to delete mine I will add his simplified edit. Change
if (ans2.equalsIgnoreCase("bag")) {
to
if (ans.trim().equalsIgnoreCase("bag")) {
then no need for
String ans2 = ans.trim();
But using a second variable may be better for readibility or functionality in certain situations
Edit To take care of in between spaces you might try
if (!ans.contains("") && ans.trim().equalsIgnoreCase("bag")) {
Not sure why that doesn't work but you can use the replace
function for Strings
String ans2 = ans.replace(" ", "");
if (ans2.trim().equalsIgnoreCase("bag")) {
Upvotes: 2