-1

So I am working on a project in java and I have just a quick question.

I have a method that is receiving a string and I want to strip out the spaces and check that is is not empty. So far I have the below in place however it doesn't seem to be working properly.

public static Boolean isValid(String s) {
    s.replace(" ", "");
    if (s == ""){
        return false;
    }
    else {
        return true;
    }
}

Any help would be appreciated :) Ta

Carl
  • 548
  • 1
  • 4
  • 21

7 Answers7

6

You can try with this:

public static Boolean isValid(String s) {
    return (!s.trim().isEmpty());
}
vefthym
  • 7,422
  • 6
  • 32
  • 58
jjlema
  • 850
  • 5
  • 8
  • Actually, this does only remove the leading and trailing spaces. `s.replace()` will also replace the spaces in the middle of the string. – Magnilex Nov 05 '14 at 11:25
  • @Magnilex if there is a white space in the middle of the string, then there are non-whitespace chars in the string... the result is the same! – vefthym Nov 05 '14 at 11:27
  • 1
    Yes, of course. You are correct. +1 for the most elegant solution. – Magnilex Nov 05 '14 at 11:37
  • I agree that this is the most elegant solution and the one that should be accepted. – vefthym Nov 05 '14 at 11:39
2

First you have forgot the assignment for s.replace(" ",""). Store that in a variable, e.g.

x = s.replace(" ","");

For string comparison use .equals() method instead of ==

Graham Borland
  • 60,055
  • 21
  • 138
  • 179
Harry
  • 3,031
  • 7
  • 42
  • 67
1

You can use the following code as well :

newString=myString.replaceAll("\\s+",""); This removes one or more spaces in between Strings as well as leading and trailing whitespaces

Use : myString.trim() to remove only leading and trailing whitespaces

and then newString.isEmpty()

You should use .equals() to compare Strings

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
1

When you're comparing strings, use .equals(). Its only in artihmetic expressions you use the == sign

TO check whether your string is empty use the .isEmpty() function

Prasanth Louis
  • 4,658
  • 2
  • 34
  • 47
1

You forgot the assignment:

s = s.replace(" ", "");

EDIT: for the comments stating that == is not working. I wanted to say that it does work for Java 7

Michael
  • 3,308
  • 5
  • 24
  • 36
1

replaceAll() method supports regular expressions as well as isEmpty() is already there in String class so we can reuse it and is safer to use here.

simply use like this:

public static Boolean isValid(String s) {
    s = s.replaceAll("\\s", "");
    if (s.isEmpty()) {
        return false;
    } 
    else {
        return true;
    }
}
Sagar Pudi
  • 4,634
  • 3
  • 32
  • 51
0

Difference between equals and == incase of String comparison is well explained in the thread

value of s.replace() should be assigned to itself or some other variable.

Community
  • 1
  • 1
Logan
  • 66
  • 6