01. cpp 字符串

CPP 中的 String 类

CPP 中的字符串已经和C 语言中的不一样了。CPP 标准库提供了string 类类型,支持对所有字符串的操作,另外还增加了其他更多的功能。

查询CPP相关类的特性及方法的网站[http://www.cplusplus.com/]


/*************************************************************************
        > File Name: cpp_str.cpp
        > Author: Lin
        > Mail: [email protected]
 ************************************************************************/

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

int main ()
{
    std::string str ("Test string");
    for ( std::string::iterator it=str.begin(); it!=str.end(); ++it)
            std::cout << *it;
    std::cout << 'n';

    return 0;
}

$ g++ cpp_str.cpp -o cpp_str
$ ./cpp_str 
Test string

/***********************************************************************
> File Name: cpp_str.cpp
> Author: Lin
> Mail: [email protected]
************************************************************************/

#include <iostream>
#include <string>

using namespace std;

int main ()
{
    string str1 = "Hello";
    string str2 = "World";
    string str3;
    int  len ;

    // 复制 str1 到 str3
    str3 = str1;
    cout << "str3 : " << str3 << endl;

    // 连接 str1 和 str2
    str3 = str1 + str2;
    cout << "str1 + str2 : " << str3 << endl;

    // 连接后,str3 的总长度
    len = str3.size();
    cout << "str3.size() :  " << len << endl;

    return 0;
}

$ g++ cpp_str.cpp 
$ ./a.out 
str3 : Hello
str1 + str2 : HelloWorld
str3.size() :  10