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中的年月日等就是用上述分割后的字段填充的。
#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中的年月日等就是用上述分割后的字段填充的。
相关文章推荐
- JAVA中String字符串特殊字符的分割问题
- python按照多个字符对字符串进行分割的方法,如标点符号,特殊字符等
- C++中将string按照空白字符分割的新方法
- 字符串分割的时候用StringUtils.split()方法代替string自带的split,特殊字符不用转义
- leetcode 434. Number of Segments in a String 按照空格分割字符串 + C++的stringstream的一个很好应用示范
- 标准C++字符串string任意分割
- C++输入一个字符串,把其中的字符按照逆序输出的两种方法
- String 使用split,replaceAll按照关键字分割字符串
- C++ 计算字符串长度之Function(包含unicode,utf-8),包含特殊字符,欧洲数字千位分隔符,逗号分隔符
- Java字符串split分割星号*等特殊字符问题
- C++输入一个字符串,把其中的字符按照逆序输出的两种方法解析
- Java中判断一个字符串String是否包含特殊字符的代码
- C++中使用指定字符分割字符串
- IOS中字符串去除特殊字符StringByTrimmingCharatersInSet
- C++字符串处理的一个例子:1.查找一个字符在字符串中第n次出现的位置。2分割字符串
- C++输入一个字符串,把其中的字符按照逆序输出的两种方法
- sql:字符串按照某个字符分割后取第几个字符串
- JAVA特殊字符分割字符串要点
- 将字符串按照指定的长度进行分割(一个中文视为两个字符)
- 按照指定的字符分割字符串形成字符数组