int find_replace_str(char str[],const char find_str[],const char replace_str[])
{
//别的操作
char *newStr=new char[newLength+1];
//对newStr的操作
str = newStr;
return count;
}
int main()
{
char *str="abceeeabceeeeabceeeeabceeeeeabc";
const char *find_str="abc";
const char *replace_str="ABCD";
cout<<find_replace_str(str,find_str,replace_str)<<" "<<str<<endl;
cin.get();
return 0;
}
main函数中的str还是之前的str,请教大神如何解决
我知道传递引用或者二级指针可以,但是这是南京大学复试的题目,函数名就是这么写的。
高洛峰2017-04-17 13:27:55
There are two problems in the program:
int find_replace_str(char str[],const char find_str[],const char replace_str[])
{
//别的操作
char *newStr=new char[newLength+1]; // <--+
//对 newStr 的操作 // <--+- (1) 此处不应新分配内存,而应直接在参数数组 str 中进行修改
str = newStr; // <--+
return count;
}
int main()
{
//char *str="abceeeabceeeeabceeeeabceeeeeabc";
// (2) 此处应该使用字符数组,而不是使用非常量(nonconst)指针。
// 定义一个字符数组会分配内存空间,然后使用拷贝(或移动)构造函数将右侧的字符串常量拷贝(或移动)到左侧的数组中。
// 定义一个字符指针不会分配内存空间,它直接指向常量字符串所在的内存空间。
char str[100] = "abceeeabceeeeabceeeeabceeeeeabc";
const char *find_str="abc";
const char *replace_str="ABCD";
cout<<find_replace_str(str,find_str,replace_str)<<" "<<str<<endl;
cin.get();
return 0;
}
So, the array allocated in str
can be passed to the function main
through the parameter find_replace_str
, and the function find_replace_str
then modifies and replaces the array, thus affecting the array allocated in main
content.
In addition, it is wrong to assign a constant string to a non-const pointer at (2)
. A constant string can only be assigned to a constant pointer or a character array. Otherwise, it would be possible to modify the string through a non-const pointer.
char *a = "abc"; // 错误
a[1] = 'd'; // 错误,尝试写入常量内存
const char *b = "abc"; // 正确,不能通过 b 修改常量字符串
char c[] = "abc"; // 正确,将常量字符串复制到字符数组中
c[1] = 'd'; // 正确,修改发生在数组中
PHPz2017-04-17 13:27:55
The meaning of the function name is very obvious. For character array operations, replace the substring that needs to be replaced.
You wrote the main function, but it is wrong to use it this way. The string is const char * and cannot be changed. You need to declare the array
char str[128] = "...";
Like this, in find_replace_str
...
{
if (找到符合的子串) {
替换掉需要替换的子串,比如 "ori" => "des";
//假设 replace_str[] = "des";
char *p = replace_str;
while (*p) { // 这里 不一定对,因为两遍的串可能不是等长的,只是示例
str[index ++] = *p++;
}
}
}