什么是最简单的方法来生成一个字符串的n个重复的字符? [英] What is the easiest way to generate a String of n repeated characters?

查看:256
本文介绍了什么是最简单的方法来生成一个字符串的n个重复的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个字符c和数字n,如何创建一个由n个重复的c组成的字符串?手动操作太麻烦了:

Given a character c and a number n, how can I create a String that consists of n repetitions of c? Doing it manually is too cumbersome:

StringBuilder sb = new StringBuilder(n);
for (int i = 0; i < n; ++i)
{
    sb.append(c);
}
String result = sb.toString();

当然有一些静态库函数已经为我做了这件事?

Surely there is some static library function that already does this for me?

推荐答案

int n = 10;
char[] chars = new char[n];
Arrays.fill(chars, 'c');
String result = new String(chars);

这篇关于什么是最简单的方法来生成一个字符串的n个重复的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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