字符串操作的全面总结( 二 )


cout << s2 << endl; //s2为bcf
return 0 。
运行结果:
字符串操作的全面总结
文章图片

运行结果
string 类型特有的版本:
string以数组的形式存储 , 可以用数组的下标进行修改操作:
代码实例:
include
include
using namespace std 。
int main
string s“hello” 。
string s2“abc” 。
s.insert0 , 3 , “A”; //在s下标是0之前插入3个A
cout << s << endl; //s为AAAhello
s.insert(5 , s2) //在AAAhello下标是5的元素之前插入abc
cout << s << endl; //s为AAAheabcllo
s2 = “123456”
cout << s << endl; //s为345AAAheabcllo
char *cp = “Stately plup Buck”
s.assign (cp , 7)
cout << s << endl; //s为Stately
s.assign(cp) //没有长度 , 默认是拷贝全部
cout << s << endl; //s为Stately plup Buck
s = “hello”
s.insert (0 , cp , 7)
cout << s cout << s s2 = “abcdef”
s.assign(s2 , 2 , 3) //s2中下标为2开始3个元素赋值给s 。
cout << s cout << s cout << s s.erase(s.size-5 , 5) //删除s中后5个
cout << s cout << s s.erase0 , 1.insert0 , “A”; //先从下标为0之前删除一个a为bc , 再插入A
cout << s s【0】 = “A” //用数组的方式处理
cout << s 运行结果:
字符串操作的全面总结
文章图片

运行结果3 适合string类型操作的函数
substr主要功能是复制子字符串 , 要求从指定位置开始 , 并具有指定的长度 。
append 方法在被选元素的结尾(仍然在内部)插入指定内容 。 提示:如需在被选元素的开头插入内容 , 请使用prepend方法 。
replace 该函数返回一个字符串 , 其中指定的字符串已经被替换为另一字符串 , 并且替换的次数也可以指定 。
代码实例:
include
include
using namespace std 。
int main
string s“Hello world” 。
string s2 = s.substr(6 , 5) //从第6个开始取5个
cout << s2 << endl ; //s2为world
s2 = s.substr(6) //从第6个开始取拷贝所有的
cout << s2 << endl ; //s2为world
s2 = s.substr(6) //s2拷贝s的全部 , 相当于s2=s
cout << s2 << endl ; //s2为Hello world
s = “C++ Primer”
s.append“ 3rd Ed”; //再s最后添加3rd Ed
cout << s<< endl ; //s为C++ Primer 3rd Ed
s = “C++ Primer”
s.inserts.size , “ 3rd Ed”; //最后插入
cout << s<< endl ; //s为C++ Primer 3rd Ed
s.replace11 , 3 , “4th”; //下标11开始3个替换4th
cout << s<< endl ; //s为C++ Primer 4th Ed
s.replace11 , 3 , “Fourth”; //下标11开始3个替换Fourth
cout << s<< endl ; //s为C++ Primer Fourth Ed
s = “C++ Primer 3rd Ed” //replace相当于先删除后插入
s.erase (11 , 3) //删除3rd
s.insert11 , “Fourth”; //插入Fourth
cout << s<< endl ; //s为C++ Primer Fourth Ed
return 0 。
运行结果:
字符串操作的全面总结


推荐阅读