开发者

Linux / C Check if a char contains spaces, the newline character or the tab character

开发者 https://www.devze.com 2023-01-05 05:09 出处:网络
I have a GtkEntry where the user has to enter an IP number or a hostname. When the button is pressed what the user typed into the entry is added to a char. How can I programma开发者_开发知识库tically

I have a GtkEntry where the user has to enter an IP number or a hostname. When the button is pressed what the user typed into the entry is added to a char. How can I programma开发者_开发知识库tically check if this char contains spaces, the newline character or the tab character? I don't need to remove them, just to know if they exist. Thanks in advance!


Take a look at character classification routines: man isspace.


Create a char array containing the characters of interest. Then use strchr() to search for the presence of the char in the string.

char charSet[] = { ' ', '\n', '\t', 0 };
char c;

// code that puts a character in c

if (strchr(charSet, c) != NULL)
{
    // it is one of the set
}


The function you are looking for is strpbrk().

#include <stdio.h>
#include <string.h>

int check_whitespace (char *str)
{
  char key[] = { ' ', '\n', '\t', 0 };
  return strpbrk (str, key);
}


Let us suppose you mean that what is typed into the GtkEntry is added to an array of char (a string, in C terminology, provided that it is null terminated). Then to check if that array of char contains at least one or more of "space" characters (according to the locale, so we use isspace),

char *array;
int i;
//..
bool contains_space = false;
for(i = 0; i < strlen(array); i++) {
  if ( isspace(array[i]) ) {
    contains_space = true;
    break;
  }
}
// return contains_space

which can be turned into a function for example.


You might consider a function such as the following which counts the number of whitespace characters in the given string giving a positive integer is any are found (i.e. TRUE), zero if none are found (i.e. FALSE) and -1 on error.

#include <ctype.h>
static int
ws_count(char *s)
{
    int n = -1;
    if (s != NULL) {
        char *p;
        for (n = 0, p = s; *p != '\0'; p++) {
            if (isspace(*p)) {
                n++;
            }
        }
    }
    return n;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号