如何从字符串中一次选择两个字符?到达字符串的第 i 个位置

how to pick two characters at a time from a string? reaching ith position of a string?

本文关键字:字符串 字符 位置 两个 选择 一次      更新时间:2023-10-16

我应该如何运行 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 个问题外,您几乎做对了:

  1. 您的循环条件是错误的,可能是这样的:

    for (i = 0; i + 1 < data.size(); i+=2)

    否则,您将尝试访问字符串末尾后面的数据。在这种情况下,如果字符串长度为奇数,您将跳过 1 个符号。如果你需要处理它,你的循环应该是不同的。

  2. 您添加 2 个字符作为数字,但您应该将其设置为字符串:

    d = std::string( data[i] ) + data[i+1];