char String1 = "1234567890+-";
char String2 = "1+a";
String2 is an input and I want to check if it contains any character that is not in String1.
I have tried using strpbrk(String2,String1)
but this returns true as long as any character in String1
exists in String2
.
Is there a better way to do it?
strspn
will return the index of the first character in String2 that is not in String1. If all the characters match, the index will be to the terminating zero.
#include <stdio.h>
#include <string.h>
int main ( void) {
char *String1 = "1234567890+-";
char *String2 = "1+a";
int index = strspn ( String2, String1);
if ( String2[index]) {
printf ( "character \'%c\' not found in %s\n", String2[index], String1);
}
return 0;
}
You can use a simplified version of union-find
.
First, you loop over string1
and mark all the characters with 1
. I write simplified code, you can complete it.
char mark[255];
for(s=string1; s; s++) mark[*s]=1;
Next, you loop over string2
and check if the current char is marked.
for(s=string2; s; s++) if (!mark[*s]) printf("%c", *s);
This will print all chars from string2
that are not in string1
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.