加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C++标准模板库string类的介绍与使用讲解

发布时间:2020-12-15 04:50:20 所属栏目:百科 来源:网络整理
导读:介绍 c++中字符串string对象属于一个类,内置了很多实用的成员函数,操作简单,方便更直观。 命名空间为std,所属头文件 注意:不是 。 跟进代码会发现string其实只是basic_string模板类的一个typedef。 赋值 //方法1 string str1 = "woniu201"; //方法2 cha

介绍

c++中字符串string对象属于一个类,内置了很多实用的成员函数,操作简单,方便更直观。

命名空间为std,所属头文件 注意:不是

跟进代码会发现string其实只是basic_string模板类的一个typedef。

赋值

//方法1

string str1 = "woniu201";

//方法2

char* p = "woniu201";

string str2 = p;

遍历

//方法1 使用下标

for (int i=0; i

{

printf("%c",str1[i]);

}

//方法2 使用迭代器

string::iterator it;

for (it=str1.begin(); it!=str1.end(); it++)

{

printf("%c",*it);

}

查找

string str5 = "woniu201";

int pos1 = str5.find("n",0); //从位置0开始查找字符n在字符串str5中的位置

int pos2 = str5.find("niu",0); //从位置0开始查找字符串niu在字符串str5中的位置

int pos3 = str5.find("niu",2);//从位置0开始查找字符串niu前两个字符组成的字符串在str5中的位置

截取

string str3 = "woniu201";

string str4 = str3.substr(0,5);//返回从下标0开始的5个字符组成的字符串

其他

//字符串连接

string str6 = "woniu201";

string str7 = "hailuo201";

string str8 = str6 + str7;

//判断是否相等

bool bRet1 = (str6 == str7); //相等为true,否则为false

//判断字符串是否为空

bool bRet2 = str6.empty();

//字符串插入

string str9 = str6.insert(0,str7); //字符串str6的0位置插入字符串str7

//字符串交换

str6.swap(str7);

//判断是否包含

string::size_type idx = str6.find("woniu");

if(idx == string::npos)

{

cout << "not found" << endl;

}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对编程之家的支持。如果你想了解更多相关内容请查看下面相关链接

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读