您的位置:首页 > 编程语言 > C语言/C++

C++ 将string字符串按照特殊的多个字符分割

2014-11-10 16:43 851 查看
遇到一个任务,将用户的时间对比,然后给出差值。其中需要将string格式的时间组装成一个time_t类型。用户的输入格式是“2014-11-10 9:09:32.111”。为了组装,我必须将他们全部分割。其中发现大部分人都是按照某一个特定的字符分割的,而其还比较复杂,我想这样做效率肯定低下。因此,自己写了一个,供大家参考:

#include<iostream>
#include<string.h>
#include<vector>
using namespace std;
vector<string> split(string strTime)
{
vector<string> result;
string temp("");
strTime+='-';//字符串结束标记,方便将最后一个单词入vector
for(size_t i = 0; i < strTime.size(); i++)
{
if(strTime[i] == '-' || strTime[i] == '.' || strTime[i] == ' ' ||strTime[i] == ':')
{
result.push_back(temp);
temp = "";
}
else
{
temp += strTime[i];
}
}
return result;
}

int main()
{
string strtime="2014-11-10 14:55:40.123";
vector<string> result = split(strtime);
for(size_t i = 0; i < result.size(); i++)
{
cout<<result[i]<<" ";
}
return 0;
}


想上面这样,就可以将一个string按照一组字符分割了。分割后可以组装到其他结构中,比如struct tm中的年月日等就是用上述分割后的字段填充的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: