C++中访问std::string的字符内容

C++中访问std::string的字符内容

要访问 STL string 的字符内容,可使用迭代器,也可采用类似于数组的语法并使用下标运算符( [])
提供偏移量。要获得 string 对象的 C 风格表示,可使用成员函数 c_str (),如程序清单 16.2 所示。

0: #include <string>
1: #include <iostream>
2:
3: int main ()
4: {
5: using namespace std;
6:
7: string stlString ("Hello String"); // sample
8:
9: // Access the contents of the string using array syntax
10: cout << "Display elements in string using array-syntax: " << endl;
11: for (size_t charCounter = 0;
12: charCounter < stlString.length();
13: ++ charCounter)
14: {
15: cout << "Character [" << charCounter << "] is: ";
16: cout << stlString [charCounter] << endl;
17: }
18: cout << endl;
19:
20: // Access the contents of a string using iterators
21: cout << "Display elements in string using iterators: " << endl;
22: int charOffset = 0;
23: string::const_iterator charLocator;
24: for (auto charLocator = stlString.cbegin();
25: charLocator != stlString.cend ();
26: ++ charLocator)
27: {
28: cout << "Character [" << charOffset ++ << "] is: ";
29: cout << *charLocator << endl;
30: }
31: cout << endl;
32:
33: // Access contents as a const char*
34: cout << "The char* representation of the string is: ";
35: cout << stlString.c_str () << endl;
36:
37: return 0;
38: }

输出:

Display elements in string using array-syntax:
Character [0] is: H
Character [1] is: e
Character [2] is: l
Character [3] is: l
Character [4] is: o
Character [5] is:
Character [6] is: S
Character [7] is: t
Character [8] is: r
Character [9] is: i
Character [10] is: n
Character [11] is: g
Display elements in string using iterators:
Character [0] is: H
Character [1] is: e
Character [2] is: l
Character [3] is: l
Character [4] is: o
Character [5] is:
Character [6] is: S
Character [7] is: t
Character [8] is: r
Character [9] is: i
Character [10] is: n
Character [11] is: g
The char* representation of the string is: Hello String

分析:
上述代码演示了访问 string 内容的多种方式。迭代器很重要,因为很多 string 成员函数都以迭代器
的方式返回其结果。 第 11~17 行使用 std::string 类实现的下标运算符( [])以类似数组的语法显示 string
中的字符。注意,这个运算符要求提供偏移量,如第 16 行所示。因此,确保不超出 string 的边界很重
要,即读取字符时,提供的偏移量不能大于 string 的长度。第 24~30 行也逐字符显示 string 的内容,
但使用的是迭代器。

对C++编程技术感兴趣的朋友请点击这里:零声学院C/C++服务器课程

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值