C++之字符串
作者:Devzhang 发布时间:[ 2016/12/7 9:58:57 ] 推荐标签:C++ .NET
字符串是n(>=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;
}
相关推荐

更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11