温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在C++中使用string类

发布时间:2021-03-25 17:17:59 来源:亿速云 阅读:151 作者:Leah 栏目:编程语言

本篇文章给大家分享的是有关如何在C++中使用string类,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

赋值

 //方法1  string str1 = "woniu201";  //方法2  char* p = "woniu201";  string str2 = p;

遍历

 //方法1 使用下标  for (int i=0; i<str1.length(); 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", 0, 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;   }

以上就是如何在C++中使用string类,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI