首页 / C++ / C++中的string类用法简介
C++中的string类用法简介
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++中的string类用法简介,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1655字,纯文字阅读大概需要3分钟。
内容图文
C++中的string类用法简介
string转换为char*
#include <iostream>
#include<string>
using namespace std;
int main()
{
string str = "hello world";
const char* pszStr = str.c_str(); //转为const char*
cout << pszStr << endl;
getchar();
return 0;
}
计算string长度、string字符串比较
string str = "hello world";
int len = str.length();
cout << len << endl;
if (0 == str.compare("hello world"))
{
cout << "相等" << endl;
}
string对象判空
使用empty()方法进行判断
string str = "";
if (str.empty())
{
cout << "字符串为空" << endl;
}
char*、char[]转换为string
将char*、char[]转换为string类型时,直接进行赋值操作即可。实际上是将char*、char[]定义的字符串的首地址赋值给string对象了。
const char* pszName = "title";
char pszCamp[] = "测试文本";
string strName = pszName;
string strCamp = pszCamp;
cout << strName << endl;
cout << strCamp << endl;
string类的find方法
使用string类的find方法,在字符串中检索字符串是否存在。
string str = "hello world";
auto pos = str.find('9', 0);
cout << pos << endl;
if (pos == string::npos) {
cout << "未找到" << endl;
}
string类的insert方法
使用string类的insert方法,向字符串中插入字符(串).
string str = "hello world";
str.insert(4, "rg");
cout << str << endl;
int类型转为string类的方法
使用stringstream类
#include <iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
int nNum1 = 123;
stringstream ss;
ss << nNum1;
string str = ss.str();//转为string类型
cout << str << endl;
string str3;
ss >> str3; //给string赋值
cout << str3 << endl;
int nNum2 = 456;
string str4;
str4 = to_string(nNum2); //使用to_string函数
cout << str4 << endl;
getchar();
return 0;
}
删除子串
string sl("real steel");
sl.erase(1, 2); //删除子串(1,2)
sl.erase(5);//删除下标为5及其后面的所有字符
内容总结
以上是互联网集市为您收集整理的C++中的string类用法简介全部内容,希望文章能够帮你解决C++中的string类用法简介所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。