[C++] string

string类包含了大量的方法接口用于操作字符串。string头文件和string.h、cstring两种头文件没有关系,后两种是用于兼容C风格的字符串函数的库,不支持string类。

初始化

 

构造

 

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

int main()
{
    string one("ingy win!");
    cout<<one<<endl;
    string two(20, '$');
    cout<<two<<endl;
    string three(one);
    cout<<three<<endl;
    one += "opp!";
    cout<<one<<endl;
    two="ing test ";
    three[0]='P';
    string four;
    four=two+three;
    cout<<four<<endl;
    char alls[]="all ingy test code!";
    string five(alls, 20);
    cout<<five<<"!\n";
    string six(alls+6, alls+10);
    cout<<six<<", ";
    string seven(&five[6], &five[10]);
    cout<<seven<<"...\n";
    string eight(four, 7, 16);
    cout<<eight<<" in motion!"<<endl;

    return 0;
}

I/O

 对于C风格字符串,有三种输入方式方式,而string类有两种

char val[100];
cin >> val;   //输入一个字符串,如果输入超过100个字符,则会发生错误
cin.getline(val, 100);  //输入一行,需要指明输入的字符数
cin.get(val, 100);  //输入,需要指明输入的字符数

string str;
cin >> str;   //输入一个字符串,自动调整大小,所以可以无限输入字符
getline(cin, str);  //输入一行,无需指明字符数,可以自由输入
#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;

int main()
{
    ifstream fin;
    fin.open("test.txt");
    if(!fin.is_open())
    {
        cout << "can't open file. Bye. \n";
        exit(1);
    }

    string item;
    int count = 0;
    getline(fin, item, ':');
    while(fin)
    {
        ++count;
        cout << count <<": \n"<< item <<endl;
        getline(fin, item, ':');
    }
    cout << "Done\n";
    fin.close();

    return 0;
}

 

使用

 

字符串种类

 

posted @ 2018-04-02 11:48  ingy  阅读(119)  评论(0编辑  收藏  举报