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.
To handle fixed-length strings in C++, use C lib functions, such as
strncpy
.If you are using std::string, look at
substr
to copy the first part of a string, the constructorstring(const char *s, size_t n)
to create a string of lengthn
with contents
(repeated) andreplace
to replace parts of your empty string, these will do the job for you.For null terminated strings, you can use sprintf.
Example:
%-*.*s
format specifiers adjust string's size and add extra spaces if it's necessary.substr
andresize
/replace
will do what you want:If you want something reusable you can write a couple of helper functions:
This prints: