将一个字符串中的字符push_back到另一个字符串

push_back a char from a string to another string

本文关键字:字符串 push 字符 back 另一个 一个      更新时间:2023-10-16

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

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

噢�

您正在从目标字符串中获取长度,该字符串仍然是空的,并且根本不会执行 while 循环。

改变

while(i< foo.length()){

while(i< fooz.length()){

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

这个使用删除算法,该算法提供了一系列要擦除的元素。

#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;
}
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()。