简体   繁体   English

比较两个字符串时,如何在不使用类或库的情况下不找到字符串数组中的第一个字符?

[英]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!" 如果是“ Hello World!” is the first string and the second string is "He". 是第一个字符串,第二个字符串是“ He”。 The program should return l , but it returns H because it still checks the first character. 程序应该返回l ,但是它返回H因为它仍然检查第一个字符。

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. 对于str中的每个字符,您的代码都会检查它是否存在于set的每个位置上。因此,当i = 0时,将'H'与set [0]比较,即j = 0时为'H'。但是当j = 1,将'H'与'e'进行比较,由于i仍为0,因此该函数返回str [0]。

Your problem will be solved if you use just one loop and check str[i]!=set[i]. 如果仅使用一个循环并检查str [i]!= set [i],则将解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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