我需要在C++的两个字符串之间找到共同的前缀

I need to find common prefix between two strings in C++

本文关键字:字符串 之间 前缀 两个 C++      更新时间:2023-10-16

我的strncpy函数不起作用,显示"cons char"类型的参数与参数类型"char"兼容 当我在主函数中调用前缀函数时,它说我必须有一个指向函数类型的指针

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void prefix(const char s1[], const char s2[], char prefix[]);  
int main()
{
char s1[30];
char s2[30];
char prefix[30];
cout << "Enter two sentences to store in two different strings" << endl;
cin.getline(s1, 30);
cin.getline(s2, 30);
prefix(s1, s2, prefix);
}
void prefix(const char a[], const char b[], char prefix[]) 
{
int size;
if (strlen(a) < strlen(b))
{
size = strlen(a);
}
else if (strlen(a) > strlen(b))
{
size = strlen(b);
}
else
{
size = strlen(a);
}

for (int i = 0; i < size; i++) 
{
if (a[i] != b[i]) 
{
strncpy(a, b, size);
}
}
}

不确定您的确切错误,但它可能像"错误 C2064:术语未计算为采用 3 个参数的函数"或"错误:'前缀'不能用作函数"。

这里的问题是你声明了一个名为prefix的局部变量,所以它将优先于全局函数prefix。某些类型的变量可能是可调用的(例如函数指针、std::function等(。

最好的解决方案通常是重命名本地,但如果需要,您可以明确告诉它使用全局范围:::prefix(s1, s2, prefix);


然而,prefix函数本身还有进一步的错误,因为strncpy(a, b, size);尝试复制到"const"字符串,这是不允许的,大概你的意思是复制到prefix字符串,并可能在那里结束循环。

但是,对于C++,通常最好使用std::string类型。您可以使用std::getline(std::cin, my_std_string)来读取行,prefix = my_std_string.substr(0, i)将是复制字符串的一部分的一种方式。

对于初学者来说,这个声明在 main

char prefix[30];

隐藏在全局命名空间中声明的同名函数。

重命名函数或变量,或者使用函数的限定名称。

此循环

for (int i = 0; i < size; i++) 
{
if (a[i] != b[i]) 
{
strncpy(a, b, size);
}
}

没有意义,在这个调用中

strncpy(a, b, size);

您正在尝试更改指针指向的常量数组a

并且函数strlen有许多冗余调用。

可以按以下方式声明和定义该函数,如下面的演示程序所示。

#include <iostream>
char * common_prefix( const char s1[], const char s2[], char prefix[] )
{
char *p = prefix;
for ( ; *s1 != '' && *s1 == *s2; ++s1, ++s2 )
{
*p++ = *s1;
}
*p = '';
return prefix;
}
int main() 
{
const size_t N = 30;
char s1[N];
char s2[N];
char prefix[N];
std::cout << "Enter two sentences to store in two different strings" << 'n';
std::cin.getline( s1, N );
std::cin.getline( s2, N );
std::cout << "The common prefix is "" << common_prefix( s1, s2, prefix ) 
<< ""n";
return 0;
}

它的输出可能看起来像

Enter two sentences to store in two different strings
Hello C#
Hello C++
The common prefix is "Hello C"