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.h
return 0;
}
C++
采用C的方式
#include <iostream>
#include <cstring>
int main()
{
//采用C的方式
char words[] = "Hello,World";
printf("%s\n",words);
printf("%d\n", strlen(words));//获取字符串的长度,需要引入cstring
return 0;
}
采用string
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1("Hello");//需引入string及命名空间std
cout << 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);//复制s1
s3 = 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位开始复制,长度为3
cout << 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::npos
cout << "rfind:" <<s1.rfind("e") << endl;//从后往前找,找不到返回string::npos
if (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