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 st开发者_如何学Pythonring.h that I can use?
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.
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
.
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.
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';
}
精彩评论