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

时间:2013-11-07 17:50:07

标签: c++ string char

我应该如何运行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位置。

3 个答案:

答案 0 :(得分:3)

你使用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;
    }
}

答案 1 :(得分:0)

除了2个问题,你几乎做对了:

  1. 你的循环条件错了,可能就是这样:

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

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

  2. 你添加2个字符作为数字,但你应该把它作为字符串:

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

答案 2 :(得分:0)

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';
}