我想做的事情是逐个字符地相互比较两个字符串。
示例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/