tags:

views:

1336

answers:

11

How do I determine if the string has any alpha character or not?

In other words, if the string has only spaces in it how do I treat it as an Empty string?

A: 

C#:

Empty means (MSDN) The value of this field is the zero-length string, "".

Therefor if you have spaces it will not be empty

private bool IsEmtpyOrContainsAllSpaces(String text)
        {
            int count = 0;
            foreach (char c in text)
            {
                if (c == ' ')
                {
                    count++;
                }
            }
            return (count == text.Length);
        }
PoweRoy
Surely you could just do:return text.Trim().Length==0;
Ian Nelson
But how fun would that be :)
erikkallen
That are other solution indeed (trim is way easier) but why the downvoting?
PoweRoy
+4  A: 

Try:

if the_string.replace(" ", "") == "":
    the_string = ""

If your language supports it, using "trim", "strip" or "chomp" to remove leading/trailing whitespace could be good too...

edit: Of course, regular expressions could solve this problem too: the_string.match("[^\s]")... Or a custom function... Or any number of things.

edit: In Caml:

let rec empty_or_space = fun
      [] -> true
    | (x::xs) -> x == ` ` and empty_or_space xs;;

edit: As requested, in LOLPYTHON:

BTW OHAI
SO IM LIKE EMPTY WIT S OK?
    LOL IZ S EMPTIE? DUZ IT HAZ UNWHITESPACE CHAREZ /LOL
    IZ S KINDA LIKE ""?
        U TAKE YEAH

    IZ S LOOK AT EASTERBUNNY OK KINDA NOT LIKE " "?
        U TAKE MEH

    U TAKE EMPTY WIT S OWN __getslice__ WIT CHEEZBURGER AND BIGNESS S OK OK
David Wolever
+1 for the lolpython example.
Neil Aitken
A: 

If you are using .NET, then the string type has a .Trim() method that strips leading and trailing spaces.

Mitch Wheat
+2  A: 

if you talking about .Net(C# or vb), then you can Trim() it to remove white spaces.

Alex Reitbort
This only removes leading and trailing whitespaces
Autodidact
@Autodidact: Well that was the question.
Alex Reitbort
A: 

If you really want to treat a string that only contains spaces as an empty string (which it isn't but that's a different story) just use whatever stripping method your language of choice provides (string.lstrip() and string.rstrip() in Python for example) and check if the resulting string has the length 0.

Horst Gutmann
+1  A: 

C++

#include <string>

bool isEmptyOrBlank(const std::string& str)
{
   int len = str.size();
   if(len == 0) { return true; }

   for(int i=0;i<len;++i)
   {
       if(str[i] != ' ') { return false; }
   }
   return true;
}

C

#include <string.h>

int isEmptyOrBlank(const char* str)
{
  int i;
  int len;

  len = strlen(str);

  //String has no characters
  if(len == 0) { return 1; }

  for(i=0;i<len;++i)
  {
     if(str[i] != ' ') { return 0; }
  }

  return 1;
}

Java

boolean isEmptyOrBlank(String str)
{
  int len = str.length();
  if(len == 0) { return true; }

  for (int i = 0; i < len; ++i)
  {
    if (str.charAt(i) != ' ')  { return false; }
  }

  return true;
}

You get the idea, you can do something similar in any language.

Stephen Pape
Neat, but I would call the function "isAllBlank" or "isBlank" since the most extended convention is that an "Empty" string is one which contains no characters at all.
Daniel Daranas
Daniel Daranas
You're right. Now it checks the string length for zero too, and takes a reference.
Stephen Pape
I'd have written "return str.trim().isEmpty()" in the Java version. It might not be as optimized, but it sure is more readable.
Joachim Sauer
what about tabs?
anon
He didn't ask for tabs, he asked if it only had 'spaces'. This could easily be expanded to check for the character not being ' ' or '\t'.
Stephen Pape
@saua: Readability isn't really a concern when you put it into it's own method. Where it's used you'd just do if(isEmptyOrBlank(blah)) {...}. Your way works too, but it has to create another copy of the String, where this shorts out at the first non space.
Stephen Pape
+4  A: 

In C# you should use String.IsNullOrEmpty.

To treat it as an empty string you can just use "" or string.Empty; To check if its empty there is a .Trim function.

Brandon
+1  A: 
if (s =~ /^\w*$/)

should work, as long as you're using Perl.

Anybody got a LOLCODE version?

David Thornley
Yea, you're right -- I think that he does want a LOLCODE version. I've added one of those :)
David Wolever
A: 

This will do the job if you are using .net.

string myStr = "    ";    
string.IsNullOrEmpty(myStr.Trim()));

If you are using .net 3.0 or above then you might like to create an extension method for this that you can use with any string.

namespace StringExtensions
{
    public static class StringExtensionsClass
    {
        public static string IsWhiteSpace(this string s)
        {
            return string.IsNullOrEmpty(s.Trim()));
        }
    }
}

You can then use this like so

string myStr = "    ";
if (myStr.IsWhiteSpace())
    Console.Write("It just whitespace");

Hope that this is what you are after.

Dean
Why did you downvote? Except for the bad naming of IsWhitespace, it's a valid answer as far as I can see.
erikkallen
A: 

The canonical method, regardless of language, is to trim the string (trim functions remove whitespace at the beginning and end of a string) and compare the result to the empty string:

if (trim(myString) == "") {
    // string contains no letters, numbers, or punctuation
}

Not all languages have a native trim function, however. Here's a good, general-purpose one for JavaScript, since I haven't seen a JS example yet:

function trim(str) {
    return str.replace(/^\\s+|\\s+$/g, "");
}

(Check out Steven Levithan's post about JavaScript trim functions for an in-depth comparison.)

Alternatively, you can use a regular expression to test "emptiness":

if (/^\s*$/.test(str)) {
    // string contains no letters, numbers, or punctuation
}

Again, not all languages natively support regular expressions. Check your language documentation.

Ben Blank
A: 

In Java:

private boolean isEmptyOrWhitespace(String str){

    str = str.replaceAll("\\s+", "");

    return (str.length()==0);

}
foljs