将迭代器存储到字符串中(Conversion、cast、append?)

Storing an iterator into a string (Conversion, cast, append ?)

本文关键字:cast append Conversion 存储 迭代器 字符串      更新时间:2023-10-16

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

但是我不知道如何使用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.
    }

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

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

你可以试试这个:

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