c++字符串简单操作回顾
一、概述
案例:回顾string字符串相关操作。
二、代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | #include <iostream> #include <string> #include <vector> using namespace std; void test(){ string str; str = "luoluoyang" ; str.assign( "luoluoyang" ,3); cout << str<<endl; string str2; str2.assign(str); cout << str2<<endl; str2.assign(str,0,2); cout <<str2<<endl; } void test1(){ //字符串拼接 string str1 = "luoluoyang " ; string str2 = "luoluoyang" ; str1+=str2; cout<<str1<<endl; str1.append( " and tony son" ); cout << str1<<endl; //查找字符串 string str = "Today is another beautiful day" ; int pos = str.find( "is" ); if (pos==-1){ cout << "str not found" <<endl; } else { cout << "str found is pos:" <<pos<<endl; } //替换 str.replace(1,5, "TTTTT" ); cout<<str<<endl; string str3 = "hello world" ; string str4 = "hello world" ; //比较操作 if (str4.compare(str3)==0){ cout << "equals" <<endl; } else { cout << "not equals" <<endl; } //查找子串 string strsub = str.substr(0,5); cout << strsub<<endl; // string email = "tony@163.com" ; int pos2 = email.find( "@" ); string posStr = email.substr(0,pos2); cout << posStr<<endl; cout << "-----------------" <<endl; //解析字符串 string str5 = "www.baidu.compare" ; vector<string> v; int start = 0; int pos3 = -1; while ( true ){ pos3 = str5.find( "." ,start); if (pos3==-1){ string tempstr = str5.substr(start,str5.size()-start); v.push_back(tempstr); break ; } string tempstr = str5.substr(start,pos3-start); v.push_back(tempstr); start = pos3+1; } for (vector<string>::iterator it = v.begin();it!=v.end();it++){ cout << *it <<endl; } cout << "------------" <<endl; //插入字符 string str6 = "luoluoyang" ; str6.insert(0, "222" ); cout << str6<<endl; //删除字符 str6.erase(0,3); cout <<str6<<endl; //string和char *str相互转换 char *str7 = "tony" ; string str8(str7); cout <<str8<<endl; string str9 = "kiki" ; const char *str10 = str9.c_str(); cout << str10<<endl; } int main( int argc, char const *argv[]) { // test(); test1(); return 0; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
2013-10-19 Java UDP和TCP的区别
2012-10-19 Android推送