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 programmatically 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!
views:
109answers:
5Take 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
}
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;
}
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);
}