How to copy string into fixed length string in C++
I have a string which I want to cop开发者_JAVA技巧y 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.
s.resize(expected_size,' ');
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.
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;
}
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 |
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.
To handle fixed-length strings in C++, use C lib functions, such as strncpy
.
精彩评论