📜  不使用strcmp()函数比较两个字符串的C程序

📅  最后修改于: 2021-04-22 04:17:26             🧑  作者: Mango

给定两个字符串s1s2 ,任务是编写C程序,比较两个字符串而不使用strcmp()函数。如果字符串相等,则打印“相等字符串”,否则打印“不相等字符串”

例子:

方法:比较两个字符串时,可能会发生三种情况:

  1. 两个字符串相同,意味着两个字符串之间的ASCII值之差为0
  2. 两个字符串不同,意味着第一个字符串中第一个不匹配字符的ASCII值小于第二个字符串,则两个字符串之间的差为(<0)
  3. 两个字符串不同,意味着第一个字符串中第一个不匹配字符的ASCII值大于第二个字符串,则两个字符串之间的差为(> 0)

基于上述三个条件,这个想法是由一个给定的一个字符串的每一个字符进行比较,每当条件2或3中发生然后打印“不等字符串”打印其他“平等字符串”。

下面是上述方法的实现:

C
// C program to compare the two strings
// without using strcmp() function
#include 
  
// Function that compares the two string
void compareStrings(char* x, char* y)
{
    int flag = 0;
  
    // Iterate a loop till the end
    // of both the strings
    while (*x != '\0' || *y != '\0') {
        if (*x == *y) {
            x++;
            y++;
        }
  
        // If two characters are not same
        // print the difference and exit
        else if ((*x == '\0' && *y != '\0')
                 || (*x != '\0' && *y == '\0')
                 || *x != *y) {
            flag = 1;
            printf("Uequal Strings\n");
            break;
        }
    }
  
    // If two strings are exactly same
    if (flag == 0) {
        printf("Equal Strings\n");
    }
}
  
// Driver Code
int main(void)
{
    // Given strings s1 and s2
    char s1[20] = "python";
    char s2[20] = "dsa";
  
    // Function Call
    compareStrings(s1, s2);
    return 0;
}


输出:
Uequal Strings

时间复杂度: O(N)
辅助空间: O(1)

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。