سؤال

I have a function which takes a char* of variable length and the length. I want to check if its contents are all white spaces.

It being a variable length, means I cant use a memcmp because I dont know how long to make the second parameter.

Any thoughts on a neat way to check it with out iterating over each character of the string?

هل كانت مفيدة؟

المحلول

A reasonably efficient way to answer this exact requirement is:

bool is_whitespace(const char* p, size_t n)
{
    while (n--)
        if (!isspace(static_cast<unsigned char>(*p++)))
            return false;
    return true;
}

More generally, it's a good idea to try to store such data in std::string variables, which makes solutions like Konrad's find_first_not_of more efficient and convenient.

*Thanks to Steve for the comment re isspace on some platforms with non-ASCII string content... e.g. http://msdn.microsoft.com/en-us/library/ms245348.aspx.

نصائح أخرى

Just walk over the chars and check for whitespace (e.g. using the isspace function).

Alternatively, convert the char* to a std::string and use string functions, i.e. find_first_not_of. For example, using the “conventional” whitespace characters in pre-Unicode encodings:

bool is_all_spaces(char const* text, unsigned len) {
    string str(text, len);
    return str.find_first_not_of(" \t\r\n\v\f") == string::npos;
}

A more fancy whitespace recognition would cope with arbitrary text encodings / locales. For that reason, using isspace is probably superior to the find_first_not_of approach.

In either case, using memcmp in C++ is ill-advised anyway and you should generally prefer C++ strings to C-style char arrays.

If you want to know if a certain character in a string is of a certain value, and you want to know that for all characters in the string, you need to iterate over the string. No way around that. Even memcmp loops over the string, it's just hidden from you.
Edit: Thought I'd provide a simple implementation for variable length strings:

bool is_only_space(const char* str){
  while(*str != '\0'){
    if(*str != ' ')
      return false;
    ++str;
  }
  return true;
}

Of course, this only works for null-terminated strings, but that should be a given.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top