string类

常用的构造函数

  • string(); // 默认构造函数,建立一个长度为0的串
    例:
    string s1;
  • string(const char *s); // 用指针s所指向的字符串常量初始化string对象
    例:
    string s2 = "abc";
  • string(const string& rhs); // 复制构造函数
    例:
    string s3 = s2;

    常用操作

    s + t 将串s和t连接成一个新串
    s = t 用t更新s
    s == t 判断s和t是否相等
    s != t 判断s和t是否不等
    s < t 判断s是否小于t(按字典顺序比较)
    s <= t 判断s是否小于或等于t(按字典顺序比较)
    s > t 判断s是否大于t(按字典顺序比较)
    s >= t 判断s是否大于或等于t(按字典顺序比较)
    s[i] 访问串中下标为i的字符

    例子:

string s1 = "abc", s2 = "def";
string s3 = s1 + s2; // 结果是"abcdef"
bool s4 = (s1 < s2); // 结果是true
char s5 = s2[1]; // 结果是&#39;e&#39;
#include <iostream>
#include <string>
using namespace std;

// 根据value的值输出true或false
// title为提示文字
inline void test(const char* title, bool value)
{
    cout << title << "returns" << (value ? "true" : "false") << endl;
}

int main()
{
    string s1 = "DEF";
    cout << "s1 is " << s1 << endl;
    string s2;
    cout << "Please enter s2: ";
    cin >> s2;
    cout << "length of s2: " << s2.length() << endl;

    // 比较运算符的测试
    test("s1 <= \"ABC\"", s1 <= "ABC");
    test("\"DEF\" <= s1", "DEF" <= s1);

    // 连接运算符的测试
    s2 += s1;
    cout << "s2 = s2 + s1: " << s2 << endl;
    cout << "length of s2: " << s2.length() << endl;

    return 0;
}
/*
s1 is DEF
Please enter s2: wearetheworld
length of s2: 13
s1 <= "ABC"returnsfalse
"DEF" <= s1returnstrue
s2 = s2 + s1: wearetheworldDEF
length of s2: 16
*/

输入整行字符串

  • getline可以输入整行字符串(要包含string头文件)。
    例如:
    getline(cin, s2); // cin表示读入键盘输入,后面会讲到io等。
  • 输入字符串事,可以使用其他分隔符作为字符串结束的标志(例如分号、逗号),而普通的只能规定为" "。将分隔符作为getline的第3个参数即可。
    例如:`getline(cin, s2, ',');
#include <iostream>
#include <string>
using namespace std;

int main()
{
    for (int i = 0; i < 2; i++)
    {
        string city, state;
        getline(cin, city, &#39;,&#39;);
        getline(cin, state);
        cout << "City:" << city << " State:" << state << endl;
    }

    return 0;
}
/*
Beijing,China
City:Beijing State:China
San Francisco,the United States
City:San Francisco State:the United States
*/