JimR
JimR

Reputation: 2225

Detecting if a string is just made up of spaces?

What's the most efficient/safest way to check if a string in C is made up only of spaces? Do I need to write a function myself to check or is there one in string.h that I can use?

Upvotes: 2

Views: 307

Answers (4)

user2100815
user2100815

Reputation:

Well, writing your own is trivial:

int IsSpaces( char * s ) {

    while ( * s ) {
        if ( ! isspace( * s ) ) {
            return 0;
        }
        s++;
    }
    return 1;
}

Anything you use from the standard library is not likely to be much more efficient.

Upvotes: 5

orlp
orlp

Reputation: 117661

When you say space, do you mean exactly or a spacing character?

However, there is no such function, this works though:

int isonlyspaces(char *str) {
    while (*str++ == ' ');
    return --str == '\0';
}

If you mean spacing characters instead of a literal space, this version is appropriate:

int isonlyspaces(char *str) {
    while (isspace(*str++));
    return --str == '\0';
}

Upvotes: 1

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

Try this:

if (!s[strspn(s, " ")]) /* it's all spaces */

If you want to also include tabs, newlines, etc. in your definition of "spaces", simply add them to the second argument of strspn.

Upvotes: 5

ypnos
ypnos

Reputation: 52317

man string.h brought me to the following manpage.

NAME strspn, strcspn - search a string for a set of characters

SYNOPSIS

   #include <string.h>

   size_t strspn(const char *s, const char *accept);

   size_t strcspn(const char *s, const char *reject);

DESCRIPTION

  • The strspn() function calculates the length of the initial segment of s which consists entirely of characters in accept.

  • The strcspn() function calculates the length of the initial segment of s which consists entirely of characters not in reject.

Upvotes: 1

Related Questions