目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)

Goal is to find common prefix between two c strings (must use specific function header)

本文关键字:前缀 函数 两个 目标 之间 字符串      更新时间:2023-10-16

我在主函数中调用函数时遇到问题
函数定义是常量字符,我正在使用无法传递的字符串 函数"char prefix[]"的最后一个定义不知道如何处理它

#include <iostream>
#include <string>
using namespace std;
void prefix(const char s1[], const char s2[], char prefix[]);  //Don't know what's the use of char prefix[]
int main()
{
string s1;
string s2;

cout << "Enter two sentences to store in two different strings" << endl;
getline(cin, s1);
getline(cin, s2);
const char *char1 = &s1[0];
const char *char2 = &s2[0];
prefix(char1, char2, );
return 0;
}
void prefix(const char a[], const char b[], char prefix[]) 
{
int i = 0;
for (; a[i] != 0 /* not a null char */ && a[i] == b[i] /* chars are 
equal */; ++i)
prefix[i] = a[i]; // copy char to prefix
prefix[i] = 0; // null terminate prefix
}

为前缀分配内存,并将指针传递给此内存:

#include <iostream>
#include <memory>
#include <string>
using std::cin;
using std::cout;
using std::getline;
using std::string;
void prefix(const char s1[], const char s2[], char prefix[]);
int main()
{
string s1;
string s2;
cout << "Enter two sentences to store in two different stringsn";
getline(cin, s1);
getline(cin, s2);
const char *char1 = &s1[0];
const char *char2 = &s2[0];
std::unique_ptr<char[]> p = std::make_unique<char[]>(std::min(s1.length(), s2.length()));
prefix(char1, char2, p.get());
cout << p.get();
return 0;
}
void prefix(const char a[], const char b[], char prefix[]) 
{
int i = 0;
for (; a[i] != 0 && a[i] == b[i]; ++i)
prefix[i] = a[i];
}