一个朋友问我string类使用地址传递出错了
原码,如下所示
2 #include <iostream>
3 #include <string>
4 #include <cctype>
5
6 using namespace std;
7
8 int replace(string *str,string c1,string c2);
9
10
11 int main()
12 {
13 int b;
14 string a = "wocanimadelajicccc";
15 // int num = a.size();
16 // int count = 0;
17 b=replace(a,"c","h");
18 cout << a<< endl;
19 cout <<b<< endl;
20 return 0;
21 }
22
23 int replace(string *str,string c1,string c2)
24 {
25 int count = 0;
26 while((*str)!="\0")
27 {
28 if((*str) == c1)
29 {
30 *str = c2;
31 count++;
32 }
33 str++;
34 }
35 return count;
36 }
地址传递,仅仅将首地址传递参数。
修改代码如下所示
#include <iostream>
#include <string>
using namespace std;
int replace(char *b,char c1,char c2);
int replace(string& b,char c1,char c2);
int main()
{
int b,c;
string a= "wocanimlajccccc";
b = replace(&a[0],'c','n');
c = replace(a,'c','n');
cout <<a <<endl;
cout <<b <<endl;
cout <<c <<endl;
return 0;
}
int replace(char *b ,char c1,char c2)
{
int count = 0;
cout <<b <<endl;
cout <<b[2] <<endl; //测试
for(int i=0;b[i]!='\0';i++)
{
if(b[i]==c1)
{
b[i] = c2;
}
count ++;
}
return count;
}
int replace(string& b,char c1,char c2)
{
int count = 0;
cout <<b <<endl;
cout <<b[2] <<endl; //测试
for(int i=0;b[i]!='\0';i++)
{
if(b[i]==c1)
{
b[i] = c2;
}
count ++;
}
return count;
}
反思
能不能使用replace(string *str ,char c1,char c2)