简体   繁体   中英

How do you find first character NOT in string array without using classes or libraries when comparing two strings?

I am trying to compare two string arrays, but am not allowed to use classes or libraries to assist.

The issue I have with this is that if one string is more than one character, then it compares the whole string to again, even though it already checked the first one.

char *find_first_not_in_the_set(char *str, const char *set)
{
    for(int i = 0; *(str + i) != '\0'; i++)
    {
        for(int j = 0; *(set + j) != '\0'; j++)
        {
            if(str[i] != set[j])  
            {
                return &(str[i]);
            }
        }
    }
    return NULL;
}

If "Hello World!" is the first string and the second string is "He". The program should return l , but it returns H because it still checks the first character.

I'd rather use this:

bool matrix[256] = {0};
int length = strlen(set);
// remember all characters we have in the 'set'
for( int i=0; i<length; i++) matrix[set[i] & 0xFF] = 1;

length = strlen(str);
// now check the characters from 'str'
for( int i=0; i<length; i++) {
    if( ! matrix[str[i] & 0xFF] ) {
        printf( "Found: %c", str[i] );
        break;
    }
}

For every character in str, your code checks if it is present on each and every position in set.Thus, when i=0 'H' is compared with set[0] ie 'H' for j=0.But when j=1,'H' is compared with 'e' and this causes the function to return str[0] because i is still 0.

Your problem will be solved if you use just one loop and check str[i]!=set[i].

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM