如何在C++中从字符串中分割字符
How do I split characters from a string in C++?
例如,如果我想将"A123456789";转换成10个不同的字符串或整数,我该怎么做?
类似:
T129542154
进入:
String s = T
int 1=1
int 2=2
int 3=9
int 4=5
int 5=4
int 6=2
int 7=1
int 8=5
int 9=4
我在谷歌上搜索过,但大多数都是将单词与短语分开,或者有一些特殊的字符要分开,而不是将单个字符分开。
由于输入字符串正好是10个字符,由一个后面跟着9位数字的字母组成,因此可以很容易地将单个字符分隔为变量,例如:
std::string input = "T129542154";
std::string s(input, 0, 1);
int i1 = input[1] - '0';
int i2 = input[2] - '0';
int i3 = input[3] - '0';
int i4 = input[4] - '0';
int i5 = input[5] - '0';
int i6 = input[6] - '0';
int i7 = input[7] - '0';
int i8 = input[8] - '0';
int i9 = input[9] - '0';
简单的方法类似于
#include <string>
#include <algorithm>
std::string s = "S124822854"; // 1 letter, followed by 9 digits
char letter = s[0];
int digits[9];
std::transform(s.begin() + 1, s.end(), digits, [](char ch){ return ch - '0'; });
这使用一个数组来保存整数(您可以很容易地使用std::vector
或std::array
(。
int length = s.size();
vector<int> sint, vector<char> schar; vector<int> whatitis;
for(int i=0; i<length; i++){
if(s[i]>='0' && s[i]<='9'){
sint.push_back(s[i]-'0');
whatitis.push_back(1);
}
else{
schar.push_back(s[i]);
whatitis.push_back(2);
}
}
int one=0, two=0;
for(int i=0; i<length; i++){
if(whatitis[i]==1)
cout<<sint[one++];
else
cout<<schar[two++];
}
相关文章:
- 如何在C++中从字符串中分割字符
- 由cin中的字符串中未捕获空白引起的分割错误
- 按分度分割字符串
- 分割故障:核心倾倒C 矢量对字符串:
- C - 返回字符串时的分割故障
- 在结构中使用字符串时的分割故障
- 为什么当从递归函数返回字符串到C 中的Main时,我会得到分割错误
- 在字符串中计数字符出现时,C 分割故障
- 简单的字符串分配导致分割故障
- 试图进入字符串时的分割故障
- 分割故障添加了两个表示字符串的大数字
- 我应该使用哪个函数来分割字符串
- 如何使用STL分割字符串
- C++如何使用多个分隔符分割字符串流
- 使用循环将字符串分割为特定长度的子单元
- 将字符串分割为字符串向量时出现无效转换错误
- 将一行(字符串)分割成更多的字符串
- c++字符串分割和操作
- 字符串分割错误
- 将字符串分割或修剪成一行