构造以特定前缀开头的特定长度的字符串
我需要构造一个以特定前缀开头的特定长度的字符串。有没有更快的方法(在性能方面)来实现以下代码段的目标?在这里使用 char* 有什么帮助吗?
int strLen = 15;
string prefix = "1234"; // could be a number of any length less than strLen
int prefixLen = prefix.length();
string str = prefix;
for(int i=0;i<strLen-prefixLen;i++)
{
str.append("9"); // use character '9' as filler
}
printf("str: %s \n", str.c_str());
示例前缀和输出:
prefix: 123, str: 123999999999999
prefix: 1234, str: 123499999999999
在此代码中,我唯一不想更改的是 'prefix'
的类型,它应保留 string
。
I need to construct a string of a specific length starting with a specific prefix. Is there any faster way (in terms of performance) to achieve the objective of the following piece of code? Would it be of any help to use char*
here?
int strLen = 15;
string prefix = "1234"; // could be a number of any length less than strLen
int prefixLen = prefix.length();
string str = prefix;
for(int i=0;i<strLen-prefixLen;i++)
{
str.append("9"); // use character '9' as filler
}
printf("str: %s \n", str.c_str());
Sample prefix and output:
prefix: 123, str: 123999999999999
prefix: 1234, str: 123499999999999
The only thing I do not want changed in this code is the type of 'prefix'
which should remain string
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
try this:
string 类有一个重载的构造函数,采用大小和字符。
构造函数将创建一个字符串对象,其中填充重复 x 次的字符
希望这有帮助
the string class has an overloaded Constructor, taking a size and a char.
The constructor will create a string object filled with the char repeated x amount of times
Hope This Helps
试试这个:
Try this: