I know there is a way to give a value of a specific character being repeated n times to a string while declaring it, like this:
string example(int, char);
But what if I didn't give it a value initially, is it possible to use the repeated character function later?
I tried doing this but it didn't work:
string example;
example(int, char);
I got this error "call of an object of a class type without appropriate operator() or conversion functions to pointer-to-function type"
You can't do exactly that, but here's the next best thing. If you need to increase/decrease size, you can use std::string::resize()
, which has a second parameter to fill the new char
s. So try this:
std::string foo;
foo.resize(10, 'A');
std::cout << foo << '\n';
And the output will be: AAAAAAAAAA
However, note that if you try this:
std::string a = "a";
a.resize(2, 'A');
a
will become "aA"
, because it does not overwrite the previous characters, only the new empty ones. To overwrite the previous ones, you can use std::fill
:
std::string a = "aaa";
std::fill(a.begin(), a.end(), 'A');
And it'll become "AAA"
.
[EDIT] As @churill said, reusing the constructor a = std::string(10, 'A')
will also set the value of the string to "AAAAAAAAAA"
, so you can use this as a simpler approach if you don't mind losing the previous value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.