栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

string类

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

string类

文章目录
    • 常见构造
    • string类对象的容量操作
    • string类对象的访问及遍历操作
    • string类对象的修改操作

常见构造

1.string()
2.string(const char s)*
**3.string(const string&s) **

void Teststring()
{
 string s1; // 构造空的string类对象s1
 string s2("hello bit"); // 用C格式字符串构造string类对象s2
 string s3(s2); // 拷贝构造s3
}
string类对象的容量操作

size:返回字符串有效字符长度
length:返回字符串有效字符长度
capacity:返回空间总大小
empty:检测字符串释放为空串,是返回true,否则返回false
clear:清空有效字符
reserve:为字符串预留空间
resize:将有效字符的个数该成n个,多出的空间用字符’’填充

void Teststring2()
{
    string s;
    // 测试reserve是否会改变string中有效元素个数
    s.reserve(100);
    cout << s.size() << endl;
    cout << s.capacity() << endl;

    // 测试reserve参数小于string的底层空间大小时,是否会将空间缩小
    s.reserve(50);
    cout << s.size() << endl;
    cout << s.capacity() << endl;
}

void Teststring1()
{
    string s("123456789");
    s.resize(15);
    cout << s.size() << endl;
    cout << s.capacity() << endl;
    cout << s << endl;

    // 将s中有效字符个数缩小到5个
    s.resize(5);
    cout << s.size() << endl;
    cout << s.capacity() << endl;
    cout << s << endl;
}

void Teststring3()
{

    string str("Hello Bit.");

    str.reserve(111);

    str.resize(5);

    str.reserve(50);

    cout << str.size() << ":" << str.capacity() << endl;

    return 0;

}

这段代码结果是什么?

string类对象的访问及遍历操作

operator[]:返回pos位置的字符,const string类对象调用

begin+end :begin获取一个字符的迭代器 + end获取最后一个字符下一个位置的迭代器

范围for:C++11支持更简洁的范围for的新遍历方式

oid Teststring()
{
 string s("hello Bit");
 // 3种遍历方式:
 // 需要注意的以下三种方式除了遍历string对象,还可以遍历是修改string中的字符,
 // 另外以下三种方式对于string而言,第一种使用最多
 // 1. for+operator[]
 for(size_t i = 0; i < s.size(); ++i)
 cout<
 cout<<*it< 
string类对象的修改操作 

operator+=:在字符串后追加字符串str
c_str:返回C格式字符串
find+pos从字符串pos位置开始往后找字符c,返回该字符在字符串中的位置

void Teststring()
{
 string str;
 str += 'b'; // 在str后追加一个字符'b' 
 str += "it"; // 在str后追加一个字符串"it"
 cout<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/993986.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号