与配置文件#includestring.h头文件不同,#includestring头文件中的函数专门用于处理c字符串。 前者是处理c语言char数组的头文件。
函数1、运算符:=、[1]和c重载了字符串,因此可以轻松计算字符串。
# include iostream # includestringusingnamespacestd; int main ((字符串S1=' 123 ),s2='567 ); string s3=s1 s2; cout s3 endl; //实现等号赋值,加号串联cout s3[0] endl; //实现对有字符串的值的访问return 0; }输出:
123567
1
二、求长度:可同时使用length ()、size () )求长度。 length ) )获取字符串长度。 size ) )取得字符串这一容器内元素的个数
# include iostream # includestringusingnamespacestd; int main () {string s1='123 ); cout s1.length () endl; cout s1.size () endl; 返回0; }输出:
3
3
三、反转字符串: reverse(http://www.Sina.com/
1、实现所有字符串的翻转。
# include iostream # include algorithm # includestringusingnamespacestd; int main ((字符串S1=' 12345 ); 反转(S1.begin )、s1.end ); cout s1 endl; 返回0; }输出:
54321
2 .通过使用迭代器,也可以实现指定位置的翻转。
# include iostream # include string # includealgorithmusingnamespacestd; int main ((字符串S1=' 12345 ); string :3360 iterator it=S1.begin (; reverse(it、it 3; cout s1 endl; 返回0; }输出:
32145
四、判断字符串是否为空:如果empty ()为空,则值为1,反之为0
# include iostream # includestringusingnamespacestd; int main ((字符串S1=' 12345 ); if(s1.empty )==1) cout '字符串为空'; else cout '字符串不为空'; 返回0; }输出:
字符串不为空
五、字符串清除函数: clear ) )清除字符串
# include iostream # includestringusingnamespacestd; int main ((字符串S1=' 12345 ); s1.clear (; if(s1.empty )==1) cout '字符串为空'; else cout '字符串不为空'; 返回0; }输出:
字符串为空
六、删除字符串: erase ()使用erase(intx,int num ),从x位置向后删除,不含x,删除num个字符。
# include iostream # includestringusingnamespacestd; int main ((字符串S1=' 12345 ); S1.erase (0,2 ); //0位置向后删除,删除两个cout s1; 返回0; }输出:
345
七、插入函数: insert ()用于插入num个字符c (insert )、intx1、int num、char c )、从x位置向后插入) x除外。
# include iostream # includestringusingnamespacestd; int main ((字符串S1=' 12345 ); s1.in
sert(0, 1, '1');cout << s1; return 0;}输出:
112345
输出:
3
-1
输出:
1
-1
从后往前查找指定的字符或字符串,用法同上。
8.3 find_first_of()函数查找第一个等于x字符的位置。 用法同上
8.4 find_first_not_of()函数查找第一个不等于x字符的位置。 用法同上
8.5 find_last_of()函数查找最后一个等于x字符的位置(注意是查找最后一个,而不是从后往前查找)。
8.6 find_last_not_of()函数查找最后一个不等于x字符的位置。 用法同上
注意:只有find和rfind函数可以查找字符串!其他函数查找会出现值不准确的情况!
九、替换函数:replace()把0后的两个字符替换成A
#include<iostream>#include<string> using namespace std;int main() {string s1 = "12345";s1.replace(0, 2, "A");cout << s1;return 0;}输出:
A345
在做题过程中, printf往往比cout要灵活一些,尤其是在输出指定内容时, 但我们知道,printf无法输出string型字符串,我们就可以用c_str()函数进行转化后输出。
#include<iostream>#include<string> using namespace std;int main() {string s1 = "12345";printf("%s", s1.c_str());return 0;}输出:
12345
输出:
3.1415926
如果哪里有困惑,欢迎给笔者留言。
如果这篇博文对你产生了帮助,可以留下小小的一个赞哦,大家的支持是我更新的最大动力~