push_back从字符串到另一个字符串的char

时间:2016-05-27 02:14:32

标签: c++ string c++11

我试图将一些字符从一个字符串附加到另一个字符串,但我无法做到。我试过这样的事情:

std::string fooz = "fooz";
std::string foo;
int i = 0;
while(i< fooz.length()){
    if(fooz[i] != 'z'){
       foo.push_back(fooz[i]);
    }
    i++;
}

foo之后它是空的。

3 个答案:

答案 0 :(得分:4)

你从目标字符串中获取长度,该字符串仍为空,并且根本不会执行while循环。

更改

while(i< foo.length()){

while(i< fooz.length()){

答案 1 :(得分:0)

STL可以在这种情况下帮助您。

这个算法使用remove算法提供一系列要擦除的元素。

#include <string>
#include <iostream>
#include <algorithm>

int main()
{
    std::string str("aaazbbb");

    std::cout << str << std::endl;

    str.erase(std::remove(str.begin(), str.end(), 'z'), str.end());

    std::cout << str << std::endl;
}

答案 2 :(得分:-1)

std::string fooz = "fooz";
std::string foo;
int i = 0;
int len=fooz.size();
while(i< len){
    if(fooz[i] != 'z'){
       foo.push_back(fooz[i]);
    }
    i++;
}

不要在while循环中调用std :: string.size()或length()。