我需要在C++的两个字符串之间找到共同的前缀
I need to find common prefix between two strings in C++
我的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"
相关文章:
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 两个字符串之间的数学运算
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)
- 我需要在C++的两个字符串之间找到共同的前缀
- 如何在没有映射的情况下在枚举和字符串之间进行转换?
- 正则表达式匹配字符串之间的数字
- 如何更有效地计算n个字符串之间的不匹配分数?
- 最接近的字符串:在字符串阵列中找到2个字符串之间的最小距离
- 在字符串之间插入字符
- STD :: cin和Scanf()应用于字符串之间的区别
- 使用 c++ 获取两个日期与时间字符串之间的差异(以秒为单位)
- 如何在C 中的字符串之间留出空间
- 在文本中的两个非唯一字符串之间获取子弦
- 假定相同的字符串之间的比较失败' == '比较
- C++提取两个字符串之间的数据
- C++ 和 pascal 字符串之间的区别
- 如何在C++中获取子字符串并在字符串之间添加字符
- 在C++代码中,如何让用户在2个文本字符串之间输入一个数字
- 如何在Visual C 中的BSTR和32位Unicode字符串之间进行转换