2019-04-02 C++学习笔记之字符串

2019-04-02  本文已影响0人  NoelleMu

参考资料:《21天学通C++》

字符串库

读写字符串

在C++中,可以用iostream库来读写内置类型的值,如int、double等。同样,也可以用iostream和string标准库使用标准输入输出来读写string对象。

**例1 **简单string的读写

#include <iostream>
#include <string>                               //包含字符串库
using namespace std;

void main(){
    string str;                                 //定义字符串对象
    cout << "Please input string:" << endl;
    cin >> str;
    cout << "The string is:\n" << str << endl;
}

输入输出:

Please input string:
Hello World
The string is:
Hello

注意:string类型的输入操作符会忽略字符串开头所有的空格,输入时遇到空格就会停止输入,所以str的值为Hello,也就只输出了Hello。

字符串赋值

可以把一个string类型的对象赋值给另一个string对象,实现简单的字符串赋值操作。

**例2 **string对象赋值操作

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

void main(){
    string str1, str2;
    cout << "Please input str1:" << endl;
    cin >> str1;
    str2 = str1;        //字符串赋值
    cout << "str1 is:" << str1 << endl;
    cout << "str2 is:" << str2 << endl;
}

输入输出:

Please input str1:
HelloWorld
str1 is:HelloWorld
str2 is:HelloWorld

注意:str1不能为中间包含空格的字符串。

字符串比较

字符串比较操作符主要有以下几种:

注意:任何一个大写字母都小于对应的小写字母。

字符串长度和空字符串

简单地说,string对象的长度指的是string对象中字符的个数。

可以使用size()函数求字符串长度。

例3 求string对象的长度

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

void main(){
    string str = ("Welcome to 21 C++");
    int num;
    num = str.size();
    cout << "the length of " << str << " is:" << num << endl;
}

输出:

the length of Welcome to 21 C++ is:17

可以使用函数empty()来判断一个string对象是否为空,该函数返回一个bool型值,若为真表示string对象为空,否则为非空。

例4 判断string对象是否为空

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

void main(){
    string str = ("Welcome to 21 C++");
    if(str.empty())
        cout << "The str is empty." << endl;
    else
        cout << "The str is not empty." << endl;
}

输出:

The str is not empty.
上一篇下一篇

猜你喜欢

热点阅读