0%

C++之字符串

字符串是n(>=0)个字符的有限序列, 是一种典型的线性数据结构. 这些字符在内存中按顺序逐个存放, 并以结束符”\0“结尾. 字符串可以视为一个特殊的数组, 其中每个元素都是一个字符型的变量.

在C语言中, 使用字符数组存放字符串. 标准C++库中定义了string类, 并为其提供了必要的抽象来支持字符串的一些基本操作.

下面是一个示例程序, 首先接受一个含有3个空格的字符串作为输入, 然后将字符串按空格进行拆分, 得到四个独立的子串. 然后重新进行拼接, 最后用拼接后的新串判断与原字符串进行比较.

//
//  main.cpp
//  字符串
//
//  Created by Scarecrow on 16/12/4.
//  Copyright © 2016年 XB. All rights reserved.
//

#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char * argv[]) {
    // insert code here...
    
    string str = "中国 北京 五星红旗 义勇军进行曲";
    string str_temp = "";
    
    //将str的值赋给str_temp
    str_temp.assign(str);
    
    string result[4] = {""};
    int position = 0;
    for (int i = 0; i < 3; i++) {
        //找到空格的索引
        position = (int)str_temp.find(" ");
        
        //截取0到position位置的子串赋值给result[i]
        result[i] = str_temp.substr(0 ,position);
        
        //更新str_temp的值, 删除从0到第一个空格索引的子串
        str_temp = str_temp.substr(position + 1,str_temp.length() - position);
        
    }
    //for循环结束后,str_temp为空格后最后一个子串
    result[3] = str_temp;
    
    cout<<"国家: "<<result[0]<<endl;
    cout<<"首都: "<<result[1]<<endl;
    cout<<"国旗: "<<result[2]<<endl;
    cout<<"国歌: "<<result[3]<<endl;

    //交换str_temp和result[0]的值
    str_temp.swap(result[0]);
    
    for(int j = 1; j < 4; j++) {
        //拼接字符串
        str_temp+=" ";
        str_temp.append(result[j]);
    }
    
    //比较拼接后的字符串和原字符串是否相同
    int equal = str.compare(str_temp);
    if (equal == 0) {
        cout << "匹配成功"<< endl;
    }else{
        cout << "匹配失败"<< endl;
    }

    return 0;
}