标准库类型string

1.定义和初始化

初始化:拷贝初始化和直接初始化

2.string对象上的操作

 3.读写string

使用getline

#include<iostream>
#include<string>
using namespace std;

int main() {
    string    s1;
    //读取一整行
    while (getline(cin,s1))
    {
        if (!s1.empty()) {
            cout << s1 << endl;
    }
    }

}

4.处理字符串

处理每个字符?利用for语句 

#include<iostream>
#include<string>
using namespace std;
int main() {
    string    s1("Hello qqq!");
    for (auto c : s1)
        cout << c << endl;
}

 输出:

 对于S1的每个字符,输出每个字符和一个换行符。

for(declaration:expression)

  statement

其中,expression是一个对象,表示一个序列,declaration负责定义一个变量,用于访问序列中的基础元素。

举例:统计string对象中标点符号的个数。

#include<iostream>
#include<string>
using namespace std;

int main() {
    string    s1("Hello qqq!aaa?");
    cout << "S1的长度:" << s1.size() << endl;
    int num = 0;
    for (auto c : s1)
        if (ispunct(c))
            ++num;
        cout << "标点符号个数:" << num << endl;

}

输出:

 

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。