C++_string遍历,连接,替换查找

string初始化,有三种方法:s1[i],迭代器,s1.at(i)抛出异常分别如下:

void main2()
{
	string s1 = "abcdefg";
	for (int i = 0; i < s1.length(); i++)
	{
		cout << s1[i] << " ";
	}
	for (string::iterator it = s1.begin(); it != s1.end(); it++)
	{
		cout << *it << endl;
	}
	for (int i = 0; i < s1.length(); i++)
	{
		cout << s1.at(i) << endl;
	}
	try
	{
		for (int i = 0; i < s1.length() + 3; i++)
		{
			cout << s1.at(i) << " ";  //抛出异常
		}
	}
	catch (...)
	{
		cout << "发生异常\n";
	}

}

输出结果:
a b c d e f g a
b
c
d
e
f
g
a
b
c
d
e
f
g
a b c d e f g 发生异常
请按任意键继续. . .

字符串连接

//连接字符串

void main4()
{
	string s1 = "aaa";
	string s2 = "bbb";
	s1 = s1 + s2;
	cout << s1 << endl;
	string s3 = "aaa";
	string s4 = "bbb";
	s3.append(s4);
	cout << s3 << endl;
	
}

输出结果:
aaabbb
aaabbb
请按任意键继续. . .

字符串的查找和替换

// 字符串查找和替换
void main5()
{
string s1 = “there is there that the real danger is not that the computer”;
int index = s1.find(“there”, 0); //这个函数记录第一次出现的数组下标。
cout << “index” << index << endl;
//输出结果0。
int offindex = s1.find(“there”, 0);
while (offindex != string::npos)
{
cout << “offindex” << offindex << endl;
s1.replace(offindex, 3, “thg”); //这行代码是要替换的thg,
offindex = offindex + 1;
offindex = s1.find(“there”, offindex);
}
//替换
cout << s1 << endl;
}

//截断与删除

void main6()
{
string s1 = “there is there that the real danger is not that the computer”;
int index = s1.find(“there”, 0); //这个函数记录第一次出现的数组下标。
cout << “index” << index << endl;
string::iterator it = find(s1.begin(), s1.end(), “l”);
if (it != s1.end())
s1.erase(it);
cout << s1 << endl;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值