【问题标题】:Storing an iterator into a string (Conversion, cast, append ?)将迭代器存储到字符串中(转换、强制转换、追加?)
【发布时间】:2015-04-19 04:22:54
【问题描述】:

我正在尝试将一个字符串逐个字符地复制到另一个字符中。目的不是复制整个字符串,而是复制其中的一部分(我稍后会为此做一些条件..)

但我不知道如何使用iterators

你能帮帮我吗?

std::string str = "Hello world";
std::string tmp;

for (std::string::iterator it = str.begin(); it != str.end(); ++it)
    {
        tmp.append(*it); // I'd like to do something like this.
    }

【问题讨论】:

    标签: c++ string iterator


    【解决方案1】:

    为什么不使用 + 运算符来连接字符串:

    #include <iostream>
    #include <sstream>
    using namespace std;
    int main(void)
    {
        string str = "Hello world";
        string tmp = "";
    
        for (string::iterator it = str.begin(); it != str.end(); ++it)
        {
            tmp+=(*it); // I'd like to do something like this.
        }
        cout << tmp;
        getchar();
        return (0);
    }
    

    【讨论】:

    • 谢谢,我找到了另一种方法,但它有点复杂,你的解决方案看起来更好;)我将 (*it) 存储在一个字符中,并将字符附加到 str ...比你更复杂
    【解决方案2】:

    你可以试试这个:

    std::string str = "Hello world";
    std::string tmp;
    
    for (std::string::iterator it = str.begin(); it != str.end(); ++it)
    {
        tmp += *it; 
    }
    cout << tmp;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      相关资源
      最近更新 更多