String 函数

1.     substr()

对字符串进行截取

	string s = "0123456789";

	string sub1 = s.substr(5);		// 从下标为5开始一直到结尾:sub1 = "56789"
	string sub2 = s.substr(5, 3);	// 从下标为5开始截取长度为3位:sub2 = "567"

2.     c_str()

返回一个指向正规 C C C 字符串的指针, 内容与本 s t r i n g string string 串相同
注意这是一个临时指针

	char str[20];
	string s = "1234";
	strcpy(str, s.c_str());		// 将 s拷贝到 str 
	
	printf("%s", s.c_str());	// 可以直接输出 

3.     replace()

用法一:
s t r str str 替换指定字符串从起始位置 p o s pos pos 开始,长度为 l e n len len 的字符
string& replace (size_t pos, size_t len, const string& str);

	string s = "this@ is@ a test string!";
	s = s.replace(s.find("@"), 1, ""); 	// 找到第一个@位置,替换长度为1的串为空 
	 
    cout << s << endl; 		// "this is@ a test string!"

用法二:
s t r str str 替换 迭代器起始位置 到 结束位置 的字符
string& replace (const_iterator i1, const_iterator i2, const string& str);

	string s = "this@ is@ a test string!";
	s = s.replace(s.begin(), s.begin()+6, ""); 	// 用str替换从begin位置开始的6个字符  
	 
    cout << s << endl; 		// "is@ a test string!"

用法三:
s u b s t r substr substr 的指定子串(给定起始位置和长度)替换从指定位置上的字符串
string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);

    string s = "this@ is@ a test string!";  
    string substr = "12345";  
    // 用substr的指定子串(从1位置数共3个字符)替换从0到5位置上的 s
    s = s.replace(0, 5, substr, substr.find("1"), 3); 
    
	cout << s << endl;		// "123 is@ a test sting!"

4.     replace_all()

replace_all() : 进行字符串替换,并循环换到没有为止
replace_all_distinct : 进行字符串替换,只换一次

string& replace_all(string& str, const string& old_value, const string& new_value) {
	while(true) {
		string::size_type pos(0);
		if( (pos=str.find(old_value))!=string::npos )
			str.replace(pos, old_value.length(), new_value);
		else break;
	}
	return str;
}
string& replace_all_distinct(string& str, const string& old_value, const string& new_value) {
	for(string::size_type pos(0); pos!=string::npos; pos+=new_value.length()) {
		if( (pos=str.find(old_value, pos))!=string::npos )
			str.replace(pos, old_value.length(), new_value);
		else break;
	}
	return str;
}
	string str1 = "12212", str2 = "12212";
	
	cout << replace_all(str1, "12", "21") << endl;			// "22211"
    cout << replace_all_distinct(str2, "12", "21") << endl;	// "21221"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值