标准库----string专题(不断更新中......)

来源:互联网 发布:防网络诈骗手抄报内容 编辑:程序博客网 时间:2024/04/28 13:47

 string 专题

string类型支持可变长度的字符串,C++标准库将负责管理与存储字符相关的内容,以及提供各种有用的操作.

在使用时应在前面添加:

#include <string>

using std::string;

注意:有些人总在在标准库#include添加using namespace:std;但是,通常,头文件当中应该只定义确实必要的东西,这是一种好习惯

#include <iostream>

#include <string>

using std::string;

using std::cout;

using std::cin;

using std::endl; 

int main()

{

    string word;

    while(cin>>word)

       cout <<word<<endl;

    return 0;

}

注意:任何存储string的size操作结果的变量必须为string::size_type类型,特别重要的是,不要把size的返回值赋给一个int变量.

string str("some string");

for(string::size_type ix=0;ix !=str.size();++ix)

    cout<<str(ix)<<endl;

再看一个例子:

string s("Hello word!!");

string::size_type punct_cnt = 0;

for(string::size_type index = 0; index !=s.size();++index)

     if(ispunct(s[index])

         ++punct_cnt;

cout<<punct_cnt

       <<" punctuation characters in " <<s <<endl;

注意:红色的ispunct是属于标准库cctype,这是一个检测字符串的库,可以去查MSDN

建议:cctype事实上从C标准继承而来的C++版本,在C++当中最好使用cctype,虽然也有ctype.h文件,但还是建议用cctype,至于什么原因,大家可以去试一试,一般情况下不会出错,但是有些情况下就会出错

原创粉丝点击