简体   繁体   English

如何使用 string(int, char) function 添加或更改声明字符串的值?

[英]How to add or change value for a declared string using string(int, char) function?

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:我知道有一种方法可以在声明字符串时将重复 n 次的特定字符的值赋予字符串,如下所示:

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?但是如果我一开始没有给它一个值,以后是否可以使用重复的字符 function 呢?

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"我收到此错误“调用 class 类型的 object 没有适当的 operator() 或转换函数到指针函数类型”

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.如果需要增加/减少大小,可以使用std::string::resize() ,它有第二个参数来填充新的char So try this:所以试试这个:

std::string foo;
foo.resize(10, 'A');
std::cout << foo << '\n';

And the output will be: AAAAAAAAAA output 将是: 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. a将变为"aA" ,因为它不会覆盖以前的字符,只会覆盖新的空字符。 To overwrite the previous ones, you can use std::fill :要覆盖以前的,您可以使用std::fill

std::string a = "aaa";
std::fill(a.begin(), a.end(), 'A');

And it'll become "AAA" .它会变成"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. [编辑] 正如@churill 所说,重用构造函数a = std::string(10, 'A')也会将字符串的值设置为"AAAAAAAAAA" ,因此如果您不这样做,您可以将其用作更简单的方法不介意丢失以前的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM