C++字符串string类常用操作详解(一)【初始化、遍历、连接】

来源:互联网 发布:pcb雕刻软件 编辑:程序博客网 时间:2024/05/17 08:19
代码示例:
#include <iostream>#include "string"using namespace std;//字符串初始化void strInit(){cout << "字符串初始化:"  <<endl;string s1 = "abcdefg";//初始化方式1string s2("abcdefg");//初始化方式2string s3 = s2;//通过拷贝构造函数 初始化s3string s4(7,'s');//初始化7个s的字符串cout << "s1 = "<< s1 << endl;cout << "s2 = "<< s2 << endl;cout << "s3 = "<< s3 << endl;cout << "s4 = "<< s4 << endl;}//字符串遍历void strErgo(){cout << "字符串遍历:"  <<endl;string s1 = "abcdefg";//初始化字符串//通过数组方式遍历cout << "1、通过数组方式遍历:"  <<endl;for (int i = 0; i < s1.length(); i++){cout << s1[i] << " ";}cout << endl;//通过迭代器遍历cout << "2、通过迭代器遍历:"  <<endl;for(string::iterator it = s1.begin(); it!= s1.end(); it++){cout << *it << " ";}cout << endl;//通过at()方式遍历cout << "3、通过at()方式遍历:"  <<endl;for (int i = 0; i < s1.length(); i++){cout << s1.at(i) << " ";//此方式可以在越界时抛出异常}cout << endl;}//字符指针和字符串的转换void strConvert(){cout << "字符指针和字符串的转换:"  <<endl;string s1 = "abcdefg";//初始化字符串cout << "string转换为char*:"  <<endl;//string转换为char*cout << s1.c_str() <<endl;//s1.c_str()即为s1的char *形式cout << "char*获取string内容:"  <<endl;//char*获取string内容char buf[64] = {0};s1.copy(buf, 7);//复制7个元素cout << buf <<endl;}//字符串连接void strAdd(){cout << "字符串连接:"  <<endl;cout << "方式1:"  <<endl;string s1 = "123";string s2 = "456";s1 += s2;cout << "s1 = "<< s1 << endl;cout << "方式2:"  <<endl;string s3 = "123";string s4 = "456";s3.append(s4);cout << "s3 = "<< s3 << endl;}int main(){//初始化strInit();cout << endl;//遍历strErgo();cout << endl;//字符指针类型和字符串转换strConvert();cout << endl;//字符串连接strAdd();cout << endl;system("pause");return 0;}
程序运行结果:
字符串初始化:s1 = abcdefgs2 = abcdefgs3 = abcdefgs4 = sssssss字符串遍历:1、通过数组方式遍历:a b c d e f g2、通过迭代器遍历:a b c d e f g3、通过at()方式遍历:a b c d e f g字符指针和字符串的转换:string转换为char*:abcdefgchar*获取string内容:abcdefg字符串连接:方式1:s1 = 123456方式2:s3 = 123456请按任意键继续. . .


0 0
原创粉丝点击