【问题标题】:Copy length of characters from array to std::string将字符长度从数组复制到 std::string
【发布时间】:2013-07-01 03:52:07
【问题描述】:

我正在尝试将 5 个字符从字符数组复制到 std::string

char name[] = "Sally Magee";
std::string first;
copy(name, name + 5, first.begin()); //from #include <algorithm>
std::cout << first.c_str();

但是我得到了字符串加上一大堆我不想要的不可打印的字符。有任何想法吗?谢谢。

【问题讨论】:

    标签: c++ arrays string copy strncpy


    【解决方案1】:

    做吧

    char name[] = "Sally Magee";
    std::string first(name, name + 5);
    std::cout << first << std::endl;
    

    见std::string constructor链接

    【讨论】:

    • 或者:std::string first(name, 5);
    【解决方案2】:

    std::copy 算法所做的是一个接一个地复制源元素,并在每个元素之后推进目标迭代器。

    这假设

    • 目标容器的大小已设置为足以容纳您复制的所有元素,
    • 或者您使用迭代器类型,每次对目标容器进行分配时都会增加它的大小。

    因此,如果要使用std::copy算法,有两种解决方法:

    1. 在复制之前调整字符串的大小:

      #include <iostream>
      #include <string>
      #include <algorithm>
      
      int main()
      {
        char source[] = "hello world";
      
        std::string dest;
        dest.resize(5);
        std::copy(source,source+5,begin(dest));
      
        std::cout << dest << std::endl;
      
        return 0;
      }
      
    2. 使用反向插入迭代器而不是标准迭代器:

      #include <iostream>
      #include <string>
      #include <algorithm>
      #include <iterator>
      
      int main()
      {
        char source[] = "hello world";
      
        std::string dest;
        std::copy(source,source+5,std::back_inserter(dest));
      
        std::cout << dest << std::endl;
      
        return 0;
      }
      

    但是,正如其他人所指出的,如果目标只是在初始化时将前 5 个字符复制到字符串中,那么使用适当的构造函数显然是最好的选择:

    std::string dest(source,source+5);
    

    【讨论】:

      猜你喜欢
      • 2016-08-29
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      • 2011-06-09
      • 2022-01-05
      • 2021-09-29
      相关资源
      最近更新 更多