创建具有指定字符数的字符串 [英] Create string with specified number of characters

查看:56
本文介绍了创建具有指定字符数的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在用c ++初始化时创建一个说256个字符的字符串?

Is there a way to create a string of say 256 characters at initialization with c++?

我的部分作业要求我"1.创建一个256个字符的字符串.使用您的名字的重复."

Part of my assignment requires me to "1. Create a string of 256 characters. Use repetitions of your first name."

除了使用循环外,我不太确定该如何做,但是我觉得有一种更简单的方法.

I'm not quite sure of how to do this other than using a loop but I feel like there is an easier way.

推荐答案

看看

Taking a look at the constructor reference of basic_string, one can see that there is no easy way of repeating a complete string. For a single character, you could use (2) like this:

std::string s(5, 'a'); // s == "aaaaa"

要生成字符串重复,您需要一些解决方法.只需使用例如 std :: generate (对算法很有趣)填充字符串,就可以更轻松地完成此后构造.

For generating a string repetition, you'll need some workaround. It's easier to do this post-construction by simply filling the string with, for example, std::generate (having fun with algorithms).

#include <string>
#include <algorithm>

// ...

std::string pattern("Xeo ");
auto pattern_it = pattern.begin();
std::string s(256, '\0');
std::generate(s.begin(), s.end(),
    [&]() -> char { 
      if(pattern_it == pattern.end())
        pattern_it = pattern.begin();
      return *pattern_it++; // return current value and increment
    });

实时示例.

这篇关于创建具有指定字符数的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆