2

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?

6
  • What language are you talking about? Commented Mar 9, 2009 at 15:34
  • I recommend not using the word "Empty" as a synonym of "All Spaces". The convention is that an "empty" string contains no characters at all. In your case it's better to use "all blank", "all spaces", "spaces only" etc. Commented Mar 9, 2009 at 15:46
  • spaces and alphanumeric characters are not mutually-exclusive. Commented Mar 9, 2009 at 15:50
  • I think the OP should clarify if he wants "contains at least one alphanumeric character" or "contains any character different from the whitespace". Commented Mar 9, 2009 at 15:57
  • what is a alpha character? When you are asking something.. please be precise... so you can get a good answer :)
    – n00ki3
    Commented Mar 9, 2009 at 16:10

11 Answers 11

9

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
0
5

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.

3

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.

6
  • 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. Commented Mar 9, 2009 at 15:41
  • Also, the signature can be: bool isAllBlank(const std::string& str) Commented Mar 9, 2009 at 15:44
  • You're right. Now it checks the string length for zero too, and takes a reference.
    – Stephen
    Commented Mar 9, 2009 at 15:46
  • I'd have written "return str.trim().isEmpty()" in the Java version. It might not be as optimized, but it sure is more readable. Commented Mar 9, 2009 at 16:14
  • 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
    Commented Mar 9, 2009 at 16:38
2

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

2
  • This only removes leading and trailing whitespaces
    – Autodidact
    Commented Mar 9, 2009 at 16:47
  • @Autodidact: Well that was the question. Commented Mar 9, 2009 at 17:36
1
if (s =~ /^\w*$/)

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

Anybody got a LOLCODE version?

1
  • Yea, you're right -- I think that he does want a LOLCODE version. I've added one of those :) Commented Mar 9, 2009 at 16:33
0

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

0

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.

0

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.

0

The kind people a Microsoft added this method

string myStr = "    ";    
string.IsNullOrWhiteSpace(myStr)

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.

1
  • Why did you downvote? Except for the bad naming of IsWhitespace, it's a valid answer as far as I can see.
    – erikkallen
    Commented Mar 9, 2009 at 22:02
0
a = ' '
b = a if a.replace(' ','') else a.replace(' ','')
-2

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);
        }
2
  • Surely you could just do: return text.Trim().Length==0;
    – Ian Nelson
    Commented Mar 9, 2009 at 16:10
  • That are other solution indeed (trim is way easier) but why the downvoting?
    – RvdK
    Commented Mar 10, 2009 at 8:14