C
#include<stdio.h>#include<string.h>int main(){char words[] = "Hello,World";//代码等同于:char words[] = {'H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', 0};printf("%s\n",words);//打印字符串printf("%d",strlen(words));//获取字符串的长度,需要引入string.hreturn 0;}
C++
采用C的方式
#include <iostream>#include <cstring>int main(){//采用C的方式char words[] = "Hello,World";printf("%s\n",words);printf("%d\n", strlen(words));//获取字符串的长度,需要引入cstringreturn 0;}
采用string
#include <iostream>#include <string>using namespace std;int main(){string s1("Hello");//需引入string及命名空间stdcout << s1 << endl;string s2 = "n";cout << s2 << endl;string s3(8, 'x');cout << s3 << endl;cout << s1.size() << endl;//获取字符串长度return 0;}
输出结果:
Hello n xxxxxxxx 5
复制字符串
#include <iostream>#include <string>using namespace std;int main(){string s1("Hello");string s2,s3;s2.assign(s1);//复制s1s3 = s1;//通过赋值实现复制s1(内存地址不会一样,仅拷贝内容)cout << s2 << endl;cout << s3 << endl;return 0;}
Hello Hello
截取字符串
#include <iostream>#include <string>using namespace std;int main(){string s1("Hello");string s2,s3,s4;s2.assign(s1, 0, 2);//复制0位到2位s3 = s1[4];//复制单个字符s4 = s1.substr(2, 3);//从2位开始复制,长度为3cout << s2 << endl;cout << s3 << endl;cout << s4 << endl;return 0;}
He o llo
查找指定字符串
#include <iostream>#include <string>using namespace std;int main(){string s1("Helloolleh");cout << "find:" <<s1.find("ll") << endl;//从前往后找,找不到返回string::nposcout << "rfind:" <<s1.rfind("e") << endl;//从后往前找,找不到返回string::nposif (s1.find("a") == string::npos){cout << "从字符串中找不到 a" << endl;}cout << s1.find("e",3) << endl;//从前往后找,从第三个字符开始查cout << s1.find_first_of("abe") << endl;//在s1中从前向后查找 “abcd” 中任何一个字符第一次出现的地方,如果找到,返回找到字母的位置//find_last_of() 从后找return 0;}
find:2 rfind:8 从字符串中找不到 a 8 1
删除字符串
int main(){string s1("Helloolleh");cout << s1.erase(5) << endl;//第五位以后全部擦除cout << s1.erase(2,3) << endl;//删除2~3位的字符return 0;}
Hello He
替换/插入 字符串
#include <iostream>#include <string>using namespace std;int main(){string s1("Hello");cout << s1.replace(1,2,"33333") << endl;//将s1中下标2 开始的3个字符换成“33333”string s2("Hello");string s3("World");cout << s2.replace(1,2,s3,2,2) << endl;//将s2中下标1开始的2个字符换成s3中下标2开始的2个字符string s4("Hello");cout << s4.insert(1,"33333") << endl;//将"33333"插入s4下标1的位置string s5("Hello");string s6("World");cout << s5.insert(1,s6,2,3) << endl;//将s6中下标2开始的3个字符插入s5下标1的位置return 0;}
H33333lo Hrllo H33333ello Hrldello
