C程序 比较两个字符串的词性

C程序 比较两个字符串的词性

在这里,我们将建立一个C程序来比较两个字符串的词法。给出2个小写英文字母的字符串s1和s2,表示词汇学上较大的字符串。词表顺序是指单词在字典中出现的顺序。

输入:

s1 = "geeks", s2 = "geeksforgeeks

输出:

String 2 is lexicographically greater than string 1.

步骤

以遵循这些步骤。

1.使用for-loop对两个字符串进行迭代。
2.比较两个字符串的每个字符,直到找到一个不匹配的字符。
3.对于位置i的未匹配字符,如果s1[i]< s2[i],s1是lexicographically小的字符串。
4.否则,s2是词汇学上较小的字符串。
5.如果没有发现不匹配的字符,则比较两个字符串的长度。
6.较长的字符串在词汇学上是较小的。

示例:

// C program to demonstrate arranging
// strings lexicographically
#include <stdio.h>
  
void compareStrings(char* s1, char* s2)
{
    int i;
    // comparing each character
    for (i = 0; s1[i] != '\0' || s2[i] != '\0'; i++) {
        if (s1[i] > s2[i]) {
            printf("String 1 is lexicographically greater "
                   "than string 2");
            return;
        }
        else if (s2[i] > s1[i]) {
            printf("String 2 is lexicographically greater "
                   "than string 1");
            return;
        }
    }
    // comparing length of two strings
    if (s1[i] != '\0') {
        printf("String 1 is lexicographically greater than "
               "string 2");
    }
    else if (s2[i] != '\0') {
        printf("String 2 is lexicographically greater than "
               "string 1");
    }
    else {
        printf("Both strings are lexicographically equal");
    }
}
int main()
{
  
    // declaring two strings
    char s1[20] = "help";
    char s2[20] = "held";
  
    // function call
    compareStrings(s1, s2);
    return 0;
}

输出:

String 1 is lexicographically greater than string 2.
  • Time Complexity: O(N)
  • Space complexity: O(1)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

C语言 实例