创建一个包含n个字符的字符串 [英] Create a string with n characters

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

问题描述

在java中是否有办法创建具有指定数量的指定字符的字符串?在我的例子中,我需要创建一个包含10个空格的字符串。我目前的代码是:

Is there a way in java to create a string with a specified number of a specified character? In my case, I would need to create a string with 10 spaces. My current code is:

StringBuffer outputBuffer = new StringBuffer(length);
for (int i = 0; i < length; i++){
   outputBuffer.append(" ");
}
return outputBuffer.toString();

有没有更好的方法来完成同样的事情。特别是我想要一些快速的(在执行方面)。

Is there a better way to accomplish the same thing. In particular I'd like something that is fast (in terms of execution).

推荐答案

for循环将由编译器。在像你这样的情况下,你不需要自己关心优化。相信编译器。 :)

The for loop will be optimized by the compiler. In such cases like yours you don't need to care about optimization on your own. Trust the compiler. :)

编辑:顺便说一句,如果有一种方法可以创建一个包含n个空格字符的字符串,那么它的编码方式与您刚刚编写的相同。

Btw if there is a way to create a string with n space characters, than it's coded the same way like you just did.

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

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