永远相信,美好的事情即将发生!
文章目录
1. 比较操作
1.1 比较方式
- 比较字符串的ASCII码进行对比
- 左=右 返回0
- 左>右 返回1
- 左<右 返回-1
1.2 函数原型
int compare(const string &s) const;
与字符串s比较int compare(const char*s) const;
与字符串s比较
1.3 代码展示
- 左=右时
- 左>右时
- 左<右时
- 代码
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
void text01() {
//字符串的比较(类似于C里的strcmp()函数)
string s1 = "hello";
string s2 = "helpo";
if (s1.compare(s2) == 0) {
cout << "s1=s2" << endl;
}
else if (s1.compare(s2) > 0) {
cout << "s1>s2" << endl;
}
else {
cout << "s1<s2" << endl;
}
}
int main() {
text01();
return 0;
}
2. 字符读写
2.1 字符读入/访问
2.1.1 方式
- 通过
[]
下标访问 - 通过
.at()
访问
2.1.2 代码展示
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
//字符串的存取
//访问修改单个字符
void text01() {
//法①:通过 [] 访问单个字符
string s1 = "hello";
int len = s1.size();
for (int i = 0; i < len; i++) {
cout << s1[i] << " ";
}
cout << endl;
//法②:通过at方式访问单个字符
for (int i = 0; i < len; i++) {
cout << s1.at(i) << " ";
}
cout << endl;
}
int main() {
text01();
return 0;
}
2.2 修改字符
2.2.1 方式
- 使用下标
[]
直接修改 - 使用
.at()
进行修改
2.2.2 代码展示
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
//字符串的存取
//修改单个字符
void text02() {
//法①:通过[]来修改
string s1 = "hello";
s1[0] = 'p';
cout << s1 << endl;
//法②:通过s1.at()来修改
s1.at(1) = 'q';
cout << s1 << endl;
}
int main() {
//text01();
text02();
return 0;
}
![img](https://img-blog.csdnimg.cn/img_convert/a588ab9e483dd37086ee5fde9fccd55c.png)
![img](https://img-blog.csdnimg.cn/img_convert/fb80f7bb5833828718949371bec1d169.png)
**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**
**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**
**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
到真正的技术提升。**
**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**
**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**