如何从字符串中一次选择两个字符?到达字符串的第 i 个位置
how to pick two characters at a time from a string? reaching ith position of a string?
我应该如何运行 for 循环以一次从字符串中挑选两个字符?
int main{
string data;
for (i = 0; i <= data.size(); i+=2)
d = data[i] + data[i+1];
cout << "the list of two characters at a time is" << d;
}
//我想选择将我的字符串(数据)划分为例如:"你好好你好吗"一次分成两个字符的列表(空格也应该算作一个字符)并列出如下:
cout should give:
he
ll
o(space)
ho
w(space)
ar
e(space)
yo
u //the last one is appended with 8 zeros with u to make a complete pair
我不明白如何在C++中达到字符串数据的第 i 个位置。
你
用substr()
怎么样?
for (int i=0; i<data.length(); i+=2) {
if(i+2 < data.length()){ //prevent it from throwing out_of_range exception
d = data.substr(i,i+2);
cout << d << endl;
}
}
std::cout << "the list of two characters at a time is:n";
for (i = 0; i < data.size(); ++i) {
if (data[i] == ' ')
std::cout << "(space)";
else
std::cout << data[i];
if (i % 2 != 0)
std::cout << 'n';
}
除了 2 个问题外,您几乎做对了:
-
您的循环条件是错误的,可能是这样的:
for (i = 0; i + 1 < data.size(); i+=2)
否则,您将尝试访问字符串末尾后面的数据。在这种情况下,如果字符串长度为奇数,您将跳过 1 个符号。如果你需要处理它,你的循环应该是不同的。
-
您添加 2 个字符作为数字,但您应该将其设置为字符串:
d = std::string( data[i] ) + data[i+1];
相关文章:
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 尝试将字符串/字符转换为整数会产生意外结果
- 为什么没有访问所有字符串字符?
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 如何将字符串字符与结构数组进行比较?
- 将单个字符串/字符输入串行监视器
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++ C 样式字符串/字符数组的大小 - 优化
- 读取字符串字符时出错
- C++ 使用 Strtok 读取字符串字符时出错
- 如何将 int 数组的 1 个元素转换为字符串/字符
- 在另一个字符串中逐个复制字符串字符
- 将字符串字符映射到矢量
- MBED RTOS将Float转换为字符串/字符阵列
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 如何比较C++中的单个字符串字符?
- 内部字符串/字符如何在 int 和 float 中存储
- 将十六进制转换为可打印的字符串/字符
- wcscpy_s后读取字符串字符时出错
- 检查字符串字符和长度