C++String容器使用中需要注意的地方

1. size()方法的返回值问题:

    string str = "hello world";
    int len = str.size(); //不太好的写法,也可以说是错误的
    auto len = str.szie();//c++11的写法
    unsigned int len = str.size(); // 正确的写法
    int n=-1;
    str.size()<n;//此处表达式的结果为true,因为str.size()的返回值是一个无符号整数,
                //n会强转为一个很大的整数

string类中size()方法的返回值是size_type,这其实是一个无符号整型,所以如果用int去接受的话,有肯能变成一个负数

2. string中 + 的使用

string str = "hello " + "world"; //错误,不能将两个常量字符串相加给一个string赋值
string str = "hello";
string str2 = str+" world";//正确

string类中使用 + 需要注意的是,+两侧至少需要一个string类型的数据才可以

3. string的遍历

C++11提供了一种新的遍历语句,如下:

for(declaration:expression)
    statement

所以对于一个字符串的遍历我们可以这样写:

事例一:
string str = "my name is xiaoming";
int index = 0;

    for (auto c : str)
    {
        if (isspace(c))
        {
            index++;
        }
    }
    cout << index << endl;

使用auto自动推导出c的类型,并通过isspace判断c是不是一个空格。

事例二:
string str = "hello world";
int index = 0;

    for (auto &c : str)
    {
        c=toupper(c); //此处要注意,要想把str变成大写,必须用c来接收toupper的返回值
    }
    cout << str<< endl;

猜你喜欢

转载自blog.csdn.net/len_yue_mo_fu/article/details/82534969