How to copy string into fixed length string in C++

2020-03-30 06:19发布

I have a string which I want to copy into a fixed length string. For example I have a string s = "this is a string" that is 16 characters long.

I want to copy this into a fixed length string s2 that is 4 characters long. So s2 will contain "this".

I also want to copy it into a fixed length string s3 that is 20 characters long. The end of the string will have extra spaces since the original string is only 16 characters long.

标签: c++ string
6条回答
Root(大扎)
2楼-- · 2020-03-30 06:35

To handle fixed-length strings in C++, use C lib functions, such as strncpy.

查看更多
【Aperson】
3楼-- · 2020-03-30 06:36

If you are using std::string, look at substr to copy the first part of a string, the constructor string(const char *s, size_t n) to create a string of length n with content s (repeated) and replace to replace parts of your empty string, these will do the job for you.

查看更多
beautiful°
4楼-- · 2020-03-30 06:39

For null terminated strings, you can use sprintf.

Example:

   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 format specifiers adjust string's size and add extra spaces if it's necessary.

查看更多
▲ chillily
5楼-- · 2020-03-30 06:47

substr and resize/replace will do what you want:

#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;
}    
查看更多
叼着烟拽天下
6楼-- · 2020-03-30 06:48
s.resize(expected_size,' '); 
查看更多
放荡不羁爱自由
7楼-- · 2020-03-30 06:48

If you want something reusable you can write a couple of helper functions:

// 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 prints:

this|
this is a string    |
查看更多
登录 后发表回答