Reputation:
Im writing a program that takes in a string consisting of o, c, and g only. I want to make an if statement that says if the string consists of any characters other than these 3 characters, print an error message or something. This is what I have so far.
void printFunction(char *str);
int main(int argc, char **argv)
{
char *input;
input = argv[1];
if (argc == 2 && strspn(input, "ogc") != 0) //problem
{
printFunction(input); //separate function
}
else
{
printf("Uhhh ENter the correct input dufus");
}
return 0;
}
This works if all 3 characters are not present but if the string contains one of the three characters, it prints the string. Not sure how to fix this.
Upvotes: 1
Views: 61
Reputation: 882028
You're almost there. Since strspn()
gives you the length of the initial substring that consists of only certain characters, the way to tell if a string consists of only those characters is if the result is the full string length:
if (argc >= 2 && strspn(input, "ogc") == strlen(input))
The following program shows this in action(a):
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[]) {
for (int i = 1; i < argc; ++i) {
printf("%s '%s'\n",
strspn(argv[i], "cog") == strlen(argv[i]) ? "YES:" : "NO: ",
argv[i]);
}
return 0;
}
as per the following transcript:
pax:~> ./testprog cog x o g cougar 'cogito ergo sum' ccc ooo ggg gocog ""
YES: 'cog'
NO: 'x'
YES: 'o'
YES: 'g'
NO: 'cougar'
NO: 'cogito ergo sum'
YES: 'ccc'
YES: 'ooo'
YES: 'ggg'
YES: 'gocog'
YES: ''
Just note that last one, it's based on the rule that you should only reject strings that have other characters. If instead the rule is that it should have characters from that set and no others, it's a simple matter to also check that the length is non-zero.
(a) As mentioned by chux
in a comment, there's another way to do this without having to invoke strlen
, one that may be worthwhile for large strings or needing to do this a great many times per second.
Since the maximum value strspn
can return is the length of the string, you can just check the character at that index to ensure it's the string terminator. If it is, the string consisted solely of the desired character. If not, the character at that position will be the first in the string that wasn't valid.
This is likely to be a simple pointer/index add and dereference, rather than a scanning of the entire string to get the length. The expression for that would be:
argv[i][strspn(argv[i], "cog")] == '\0'
Upvotes: 2