如何在C ++中将字符串复制到固定长度的字符串中

时间:2010-02-27 10:09:03

标签: c++ string

我有一个字符串,我想复制到一个固定长度的字符串。例如,我有一个长度为16个字符的string s = "this is a string"

我想将其复制到一个长度为4个字符的固定长度字符串s2。因此s2将包含"this"

我还想将其复制到长度为20个字符的固定长度字符串s3中。字符串的结尾将有额外的空格,因为原始字符串只有16个字符长。

6 个答案:

答案 0 :(得分:6)

s.resize(expected_size,' '); 

答案 1 :(得分:3)

如果您正在使用std :: string,请查看substr以复制字符串的第一部分,构造函数string(const char *s, size_t n)以创建长度为n且内容为{s的字符串。 1}}(重复)和replace替换部分空字符串,这些将为您完成工作。

答案 2 :(得分:1)

substrresize / replace会做你想做的事:

#include <string>
#include <iostream>
using namespace std;

int main()
{
    string s = "abcdabcdabcdabcd";
    string t;
    string u;

    t = s.substr(0,4);
    u = s;
    u.resize(20, ' ');

    string v(20, ' ');
    v.replace(0, s.length(), s);

    cout << "(" << s << ")" << endl
         << "(" << t << ")" << endl
         << "(" << u << ")" << endl
         << "(" << v << ")" << endl;
}    

答案 3 :(得分:1)

如果你想要一些可重复使用的东西,你可以编写几个辅助函数:

// Non-mutating version of string::resize
std::string resize_copy(std::string const & str, std::size_t new_sz)
{
    std::string copy = str;
    copy.resize(new_sz);
    return copy;
}

void resize_to(std::string const & str, std::string & dest)
{
    dest = resize_copy(str, dest.size());
}

int main()
{
    std::string a = "this is a string";
    std::string b(4, ' ');
    std::string c(20, ' ');
    resize_to(a, b);
    resize_to(a, c);
    std::cout << b << "|\n" << c << "|\n";
}

打印:

this|
this is a string    |

答案 4 :(得分:0)

对于以null结尾的字符串,您可以使用sprintf

示例:

   char* s1 = "this is a string";
   char  s2[10];
   int   s2_size = 4;
   sprintf(s2, "%-*.*s", s2_size, s2_size, s1);
   printf("%s\n", s2);

%-*.*s格式说明符调整字符串的大小,并在必要时添加额外的空格。

答案 5 :(得分:-1)

要在C ++中处理固定长度的字符串,请使用C lib函数,例如strncpy

相关问题