string类使用地址传递进入函数+引用传递

本文分析了一个朋友关于C++ string类中通过地址传递引发的错误,重点讨论了如何正确使用`replace`函数,涉及到指针和字符串操作。作者提供了修改后的代码,并解释了为何原始代码会导致错误以及如何修正。
摘要由CSDN通过智能技术生成

一个朋友问我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)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值