c - 如何比较两个不同字符串中的每个字符?

标签 c string char max string-comparison

我想做的事情是逐个字符地相互比较两个字符串。

示例1:

字符串A:你好
字符串 B:HelloWorld

输出:你好

示例2:

字符串A:Howdy
字符串 B:Blowdy

输出:owdy

在上面的示例中,即使字符串 A 比字符串 B 具有更多字符,反之亦然,并且它们都不同,但我仍然希望输出两个字符串上相同的字符。我还希望程序在正在比较的字符串之一达到 null 时停止比较。

我已经想出了几行代码,可能可以做到这一点,但我不太确定我是否朝着正确的方向前进。

int main(){
  char stra[100];
  char strb[100];
  char strc[100];

  for(int i = 0; stra[i] != Null && strb[i] != Null; i++){
    if(stra[i] == strb[i]){
        strc[i] = stra[i];
    }
  }

  if (strc != NULL){
    printf(strc);
  }else{
    printf("both words do not match");
  }
}

最佳答案

我们初学者应该互相帮助。

任务并不像看起来那么简单。

给你。

#include <stdio.h>
#include <string.h>

void max_common_substring( const char *s1, const char *s2 )
{
    size_t max_common_length = 0;
    const char *max_start    = NULL;

    for ( ; *s1; ++s1 )
    {
        const char *p = strchr( s2, *s1 );
        if ( p != NULL )
        {
            size_t common_length = 0;
            for ( const char *q = s1; *q && *p && *q == *p; ++q, ++p )
            {
                ++common_length;                    
            }

            if ( max_common_length < common_length )
            {
                    max_common_length = common_length;
                    max_start = s1;
            }
        }
    }        

    if ( max_start != NULL )
    {
        printf( "%*.*s\n", ( int )max_common_length, ( int )max_common_length, max_start );
    }        
}

int main( void )
{
    const char *s1 = "Hello";
    const char *s2 = "HelloWorld";

    max_common_substring( s1, s2 );

    s1 = "Howdy";
    s2 = "Blowdy";

    max_common_substring( s1, s2 );
}

程序输出为

Hello
owdy

您可以优化循环

for ( ; *s1; ++s1 )

当字符串 s1 中剩余的未处理字符已经小于 max_common_length 当前计算值时,停止循环。

至于您在问题中的代码,显然它没有意义。:)

关于c - 如何比较两个不同字符串中的每个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57181235/

相关文章:

Cuda Matrix乘法程序无法通过,很奇怪的错误代码

c - 这两个指向 char 初始化的指针之间的区别

Python如何从字符串中多次出现之间获取变量

c++ - C++ 中的全局字符串数组

java - 在 Java 中将二维整数数组转换为字符和字符串

c - 不同类型的链表

c - 如何处理 OpenMP 中的数据争用?

Python:你如何准确地获取一个字符串,将其拆分、反转并重新组合在一起?

java - 在 Java 中将字符转换为整数

java - Java 中从字符串到二维字符数组