字符串是程序中经常要表达和处理的数据,我们通常是采用字符数组或字符指针来表示字符串。STL为我们提供了另一种使用起来更为便捷的字符串的表达方式:string。string类的定义在头文件<string>中。

string类其实可以看作是一个字符的vector,vector上的各种操作都可以适用于string,另外,string类对象还支持字符串的拼合、转换等操作。

下面先来看一个简单的例子:

#include <iostream>
#include <string>
using namespace std;
main()
{
    string s = "Hello! ", name;
    cin >> name;
    s += name;
    s += '!';
    cout << s << endl;
    return 1;
}

再以题1064--Parencoding为例,看一段用string作为容器,实现由P代码还原括号字符串的示例代码片段:

int m;
cin >> m; // P编码的长度
string str; // 用来存放还原出来的括号字符串
int leftpa = 0; // 记录已出现的左括号的总数
for (int j=0; j<m; j++)
{
    int p;
    cin >> p;
    for (int k=0; k<p-leftpa; k++) str += '(';
    str += ')';
    leftpa = p;
}




Comments

Good.Be the first to comment on this entry.

Post comment

comment has COPYRIGHT too!

Note: Commenter is allowed to use '@User+blank' to automatically notify your reply to other commenter. e.g, if ABC is one of commenter of this post, then write '@ABC '(exclude ') will automatically send your comment to ABC. Using '@all ' to notify all previous commenters. Be sure that the value of User should exactly match with commenter's name (case sensitive).