• frits (cs)

    If only there was a method to replace all occurrences of a string (such as " ") with an empty string. Someone should get on that.

  • Old Smith (unregistered)

    I see only one comment on that post for the frist time

  • Adam (unregistered)

    Is string unwanted 1,2,3 or 10 char long? Im amazed how you an spend time and figure out something like that and Not start thinking that this might not be the right way doing it.

  • TarquinWJ (cs) in reply to frits
    Double Spaced:
    If only there was a method to replace all occurrences of a string (such as " ") with an empty string.
    Or even (for a specific case) to "trim" all of the whitespace. These languages really need to be updated to support such advanced functionality.
  • The Nerve (unregistered)

    Fixed?

     public boolean isBlank(String str) {
      try {
         return str.trim().length() == 0;
      } catch (NullPointerException ex)
      {
      }
      return true;
     }// end
    
  • JSelf (cs) in reply to Adam
    Adam:
    Is string unwanted 1,2,3 or 10 char long? Im amazed how you an spend time and figure out something like that and Not start thinking that this might not be the right way doing it.

    CLEARLY the dev should have loaded them into an array...

  • Cheng (unregistered)

    // fixed?

    public boolean isBlank(String str) {
      String toCompare = "";
      if(str.equals(toCompare)) return true;
    
      for (int i=0;i<1000;i++){ // ok, let's hope that nobody can go farther than 1000 whitespaces
         toCompare+=" ";
         if(str.equals(toCompare)) return true;
      }
      else
         return false;
     }// end of that fix
    
  • Markus (unregistered)
    public bool isBlank(string str) {
        return string.IsNullOrWhiteSpace(str);
    }

    FTFY 4.0

  • Anonymous (unregistered) in reply to Markus
    Markus:
    public bool isBlank(string str) {
        return string.IsNullOrWhiteSpace(str);
    }

    FTFY 4.0

    The original code doesn't look much like .NET to me. the "java.lang.String" bit rather gives it away.

  • drusi (unregistered)

    The second function looks like the result of adding more Replaces until all the test strings came through as expected.

  • Severity One (cs) in reply to The Nerve
    The Nerve:
    Fixed?
     public boolean isBlank(String str) {
      try {
         return str.trim().length() == 0;
      } catch (NullPointerException ex)
      {
      }
      return true;
     }// end
    
    Ugh... well, at least you posted your code on the right site.
    public boolean isBlank( String str ) {
        return str == null || str.trim().isEmpty();
    }

    FTFY

  • Donald (unregistered)

    XML doesn't care about spaces. Why should a developer?

  • Brent (unregistered)

    Well, up to five spaces in an input field is clearly a typo and a mistake. But if the user puts SIX spaces in the field, they must have really meant it, so the field hasn't been left blank because it now contains what the user intends.

  • frits (cs) in reply to TarquinWJ
    TarquinWJ:
    Double Spaced:
    If only there was a method to replace all occurrences of a string (such as " ") with an empty string.
    Or even (for a specific case) to "trim" all of the whitespace. These languages really need to be updated to support such advanced functionality.

    What about if there are embedded tabs and such in addition to spaces? There has got to be some regular way of expressing this.

  • The Enterpriser (cs) in reply to Severity One
    Severity One:
    The Nerve:
    Fixed?
     public boolean isBlank(String str) {
      try {
         return str.trim().length() == 0;
      } catch (NullPointerException ex)
      {
      }
      return true;
     }// end
    
    Ugh... well, at least you posted your code on the right site.
    public boolean isBlank( String str ) {
        return str == null || str.trim().isEmpty();
    }

    FTFY

    Almost, you forgot the all important

    //end 
    

    which is required in order to prevent people from attempting to read past the end of the text. Think of it as an EOF for humans.

  • Airhead (cs)

    I think I have the perfect solution for PHP:

    <?php
    class SpaceClass
    {
    	public function IsSpaces($String, $Spaces)
    	{
    		return preg_match('/^ {' . $Spaces . '}$/', $String);
    	}
    
    	public function IsBlank($String, $Length = 1000)
    	{
    		$OnlySpaces = false;
    		
    		for ($i = 0; $i < $Length; $i++)
    		{
    			if (!$OnlySpaces && $this->IsSpaces($String))
    			{
    				$OnlySpaces = true;
    			}
    		}
    		
    		return $OnlySpaces;
    	}
    }
    ?>
    

    Double linefeeds are not so perfect, but I think it kinda makes sense with this class.

  • TheKoz (unregistered) in reply to The Nerve

    public boolean isBlank(String str) { return String.IsNullOrEmpty(str.trim()); }

  • SCB (unregistered) in reply to drusi
    drusi:
    The second function looks like the result of adding more Replaces until all the test strings came through as expected.
    TDD FTW!
  • TryCatchPolice (unregistered) in reply to The Nerve
    The Nerve:
    Fixed?
     public boolean isBlank(String str) {
      try {
         return str.trim().length() == 0;
      } catch (NullPointerException ex)
      {
      }
      return true;
     }// end
    

    Please don't misuse try/catch for null-checking.

    /facepalm

  • Anonymous (unregistered)

    This is easy to fix:

    public boolean isBlank(String str) {
    bool blank = true;
    for (int i = 0; i < str.Length; i++) {
    if (str.charAt(i) != ' ') {
    blank = false;
    }
    }
    return blank;
    }

  • Airhead (cs) in reply to The Enterpriser
    The Enterpriser:
    Almost, you forgot the all important
    //end 
    

    which is required in order to prevent people from attempting to read past the end of the text. Think of it as an EOF for humans.

    Everybody, stop reading! This is the last comment!

    //end

  • frits (cs) in reply to The Enterpriser
    The Enterpriser:
    Severity One:
    The Nerve:
    Fixed?
     public boolean isBlank(String str) {
      try {
         return str.trim().length() == 0;
      } catch (NullPointerException ex)
      {
      }
      return true;
     }// end
    
    Ugh... well, at least you posted your code on the right site.
    public boolean isBlank( String str ) {
        return str == null || str.trim().isEmpty();
    }

    FTFY

    Almost, you forgot the all important

    //end 
    

    which is required in order to prevent people from attempting to read past the end of the text. Think of it as an EOF for humans.

    I've actually used/seen C code with //eof on the last line of every file in a project.

  • NPEPolice (unregistered) in reply to TheKoz
    TheKoz:
    public boolean isBlank(String str) { return String.IsNullOrEmpty(str.trim()); }

    /facepalm2

  • buiatte (unregistered)

    public boolean isBlank( String str ) {

    return org.apache.commons.lang.StringUtils.isBlank( str );
    

    }

    I am amazed by the fact that most Java developers dont know (or dont care) about commons-lang (or apache commons in general)

  • Alex (unregistered)

    You're all ripping on the first example, which is fair. But the second one may actually be kind of clever:

    Suppose your requirement is you need to remove extra spaces, but not all spaces; you can't just do " "->"", and if you don't have regular expressions handy, this solution is not that bad.

    It first replaces spaces 10-for-1, twice. So unless the original string had more than 900 spaces in a row, it now has at most 9 in a row in any one place. Next it replaces 3-for-1, so any 9-space chunks become 3-space chunks. Next it does 2-for-1 twice, so those 3-space chunks become 2 and then 1-space. And now there are no extra spaces anywhere, but there are also still single spaces everywhere there should be.

    So with that second example, TRWTF is older versions of VB which lacked regular expressions, forcing this kind of solution. But the solution itself is valid.

  • Todd (unregistered)
    1. Replace all occurrences of 10 spaces with 1 space.
    2. Replace all occurrences of 3 spaces with 1 space.
    3. Replace all occurrences of 2 spaces with 1 space.
    4. Replace all occurrences of 2 spaces with 1 space.
    5. ???
    6. Profit!
  • Whatever (unregistered) in reply to Anonymous
    Anonymous:
    This is easy to fix:
    public boolean isBlank(String str) {
     bool blank = true;
     for (int i = 0; i < str.Length; i++) {
      if (str.charAt(i) != ' ') {
       blank = false;
      }
     }
     return blank;
    }

    "So this string is blank? "

  • Anon (unregistered) in reply to Alex
    Alex:
    You're all ripping on the first example, which is fair. But the second one may actually be kind of clever:

    You must be using a different definition of "clever" than the rest of us.

  • EngleBart (unregistered) in reply to drusi
    drusi:
    The second function looks like the result of adding more Replaces until all the test strings came through as expected.
    I think it is an attempt at optimization. Replace large blocks, then successively smaller blocks until you get to 2 characters.

    I have manually done similar tricks in slow text editors when dealing with large files. Here was my manual algorithm:

    do
      Replace 4 spaces to 1 space
    while numReplacements > 0
    
    // This loop should never run more than twice
    do
      Replace 2 spaces to 1 space
    while numReplacements > 0
    
  • Scott Douglas (unregistered)

    Space is big. Really big. You just won't believe how vastly, hugely, mindbogglingly big it is. I mean, you may think it's a long way down the road to the chemist's, but that's just peanuts to space

  • Alex (unregistered) in reply to Anon
    Anon:
    Alex:
    You're all ripping on the first example, which is fair. But the second one may actually be kind of clever:

    You must be using a different definition of "clever" than the rest of us.

    So you tell me, how do you replace all occurrences of 2 or more spaces with only 1 space, in VB6, with no regular expressions?

    I even googled it, and the suggested solutions include "copy the string char-by-char, skipping space chars that come after other space chars"; "while string contains ' ' replace ' '->' '".. this solution is probably faster than those, at least.

  • TGV (cs) in reply to The Nerve
    The Nerve:
    Fixed?
     public boolean isBlank(String str) {
      try {
         return str.trim().length() == 0;
      } catch (NullPointerException ex)
      {
      }
      return true;
     }// end
    
    If don't like this code either. You generate an extra string but throw it away immediately. And you interpret null as a blank string, which it isn't. Or have you been working with Oracle too much?
  • EngleBart (unregistered) in reply to Alex
    Alex:
    You're all ripping on the first example, which is fair. But the second one may actually be kind of clever:

    Suppose your requirement is you need to remove extra spaces, but not all spaces; you can't just do " "->"", and if you don't have regular expressions handy, this solution is not that bad.

    It first replaces spaces 10-for-1, twice. So unless the original string had more than 900 spaces in a row, it now has at most 9 in a row in any one place. Next it replaces 3-for-1, so any 9-space chunks become 3-space chunks. Next it does 2-for-1 twice, so those 3-space chunks become 2 and then 1-space. And now there are no extra spaces anywhere, but there are also still single spaces everywhere there should be.

    So with that second example, TRWTF is older versions of VB which lacked regular expressions, forcing this kind of solution. But the solution itself is valid.

    It is probably faster to allocate a StringBuilder as large as the current string and then copy every character from source to dest, omitting blanks if the last character was blank. Less scanning of characters (each character read exactly once) and less intermediate String object creation.

  • Dazed (unregistered) in reply to Alex
    Alex:
    It first replaces spaces 10-for-1, twice. So unless the original string had more than 900 spaces in a row, it now has at most 9 in a row in any one place. Next it replaces 3-for-1, so any 9-space chunks become 3-space chunks. Next it does 2-for-1 twice, so those 3-space chunks become 2 and then 1-space. And now there are no extra spaces anywhere, but there are also still single spaces everywhere there should be.
    Good catch - but there is still the WTF that what the code says it is doing is something totally different.
  • Anonymous (unregistered) in reply to Whatever
    Whatever:
    Anonymous:
    This is easy to fix:
    public boolean isBlank(String str) {
     bool blank = true;
     for (int i = 0; i < str.Length; i++) {
      if (str.charAt(i) != ' ') {
       blank = false;
      }
     }
     return blank;
    }

    "So this string is blank? "

    I was only joking but the code still works as advertised. "So this string is blank? " returns false.

  • David Allen (unregistered)

    The RemoveCharacters function is interesting, it was clearly built to reduce the number of Replace calls.

    It handles all cases up to 208 contiguous spaces. From 209 to 1200 it becomes progressively worse. 1200 contiguous spaces is the largest it handles correctly. It correctly handles 58.7% (704) of the cases up to 1200 spaces.

  • TGV (cs) in reply to buiatte
    buiatte:
    public boolean isBlank( String str ) {
    return org.apache.commons.lang.StringUtils.isBlank( str );
    

    }

    I am amazed by the fact that most Java developers dont know (or dont care) about commons-lang (or apache commons in general)

    I'm amazed by the fact that someone does know something hidden so deeply in apache stuff. That's just weird. The reason a developer wouldn't know, might be that it's not standard. indexOf(' ') on the other hand is...

  • EngleBart (unregistered) in reply to TGV

    trim() only returns a new object if it needs to... otherwise it returns this

    return ((st > 0) || (len < count)) ? substring(st, len) : this;

    If you want to handle NullPointerException yourself then just remove the try/catch.

  • Mike (unregistered) in reply to Cheng
    Cheng:
    // fixed?
    public boolean isBlank(String str) {
      String toCompare = "";
      if(str.equals(toCompare)) return true;
    

    for (int i=0;i<1000;i++){ // ok, let's hope that nobody can go farther than 1000 whitespaces toCompare+=" "; if(str.equals(toCompare)) return true; } else return false; }// end of that fix

    How many WTFs can you find in this code?

  • smbell (cs) in reply to Alex
    Alex:
    Anon:
    Alex:
    You're all ripping on the first example, which is fair. But the second one may actually be kind of clever:

    You must be using a different definition of "clever" than the rest of us.

    So you tell me, how do you replace all occurrences of 2 or more spaces with only 1 space, in VB6, with no regular expressions?

    I even googled it, and the suggested solutions include "copy the string char-by-char, skipping space chars that come after other space chars"; "while string contains ' ' replace ' '->' '".. this solution is probably faster than those, at least.

    You must have failed algorithmic complexity. This may be an attempt at efficiency, but it's a failed attempt because you ignore any complexity of the Replace function. Iterating over every character in the string and skipping whitespace characters will only have to iterate over the length of the string once. The 'replace blocks at a time' will have to iterate over the string for each set of blocks it replaces. I suspect, although I'm not a VB expert (thank god), that it will also allocate a comparatively large amount of additional memory in comparing and storing the various intermediate strings.

  • Mike (unregistered) in reply to frits
    frits:
    I've actually used/seen C code with //eof on the last line of every file in a project.

    This is probably due to certain older compilers (cough Watcom cough) that would choke on EOF in certain situations, making this sort of thing a best practice.

  • boog (cs)

    Criticizing their code would be too easy. So I'm going for the comments:

      * @return boolean
      * @param param
      *            java.lang.String
    

    Wow, thank god he defined the data types in the comments. As if I couldn't read them in the code. And it's really too bad that Javadoc can't figure it out automatically.

    ' Replaces the characters set in strUnwanted as spaces
    

    Replace characters as spaces. Right. Not replace spaces with spaces, as the code does. So... WTF is strUnwanted?

  • Max (unregistered) in reply to Alex
    Alex:
    You're all ripping on the first example, which is fair. But the second one may actually be kind of clever
    As we've seen all too often on this site, clever != good code

    Sure it does what it needs to without regular expressions, which conceivably could be a real restriction, but as soon as someone needs to maintain it, they have to spend some time figuring out what it actually does, and whether or not it's working properly. Something less efficient that is more obvious in how it works would probably have been a better choice.

    But then, I'm probably preaching to the choir.

  • Brent (unregistered) in reply to Anon
    Anon:
    Alex:
    You're all ripping on the first example, which is fair. But the second one may actually be kind of clever:

    You must be using a different definition of "clever" than the rest of us.

    Sounds like the way I use clever... as in "if you find yourself writing particularly clever code, you should probably stop and think about what you're doing wrong and/or what you missed".

  • frits (cs) in reply to Alex
    Alex:
    So you tell me, how do you replace all occurrences of 2 or more spaces with only 1 space, in VB6, with no regular expressions?

    I dunno maybe use Split() and manually join all non-empty elements with a space in between each one?

  • AlexB (unregistered) in reply to buiatte

    The apache commons libs are the most awsome libs out there!

    Btw i love replacing replacing replacing stuff.

  • The Corrector (unregistered) in reply to AlexB
    AlexB:
    The apache commons libs are the most bloated libs out there!

    Btw i love replacing replacing replacing stuff.

    FTFY

  • What do you expect from a Agile company (unregistered) in reply to Severity One
    Severity One:
    The Nerve:
    Fixed?
     public boolean isBlank(String str) {
      try {
         return str.trim().length() == 0;
      } catch (NullPointerException ex)
      {
      }
      return true;
     }// end
    
    Ugh... well, at least you posted your code on the right site.
    public boolean isBlank( String str ) {
        return str == null || str.trim().isEmpty();
    }

    FTFY

    Yes, but this function discounts all whitespace. You changed the spec.

  • Dirge (unregistered) in reply to Alex
    Comment held for moderation.
  • Bourne (unregistered)
    sub isBlank (B1) {
      if (index (' ', B1)) {
        B2 = eval "system ('echo '" . B1 . "' | \"sed s/\ //\")'"
        if (B2) {
          B3 = isBlank (B2)
        }
      }
      return FileNotFound
    }

Leave a comment on “Double Spaced”

Log In or post as a guest

Replying to comment #:

« Return to Article