用指定字符填充指定长度的String的最有效方法? [英] Most efficient way to fill a String with a specified length with a specified character?

查看:557
本文介绍了用指定字符填充指定长度的String的最有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上给定一个int,我需要生成一个只包含指定字符的相同长度的字符串。相关问题此处,但它与C#相关,它 重要的是什么在字符串。



问题,我的答案就是我问这个问题的原因。我不确定什么是最好的方法来表现明智。

示例



方法签名:

 字符串getPattern(int length,char character); 

用法:

  //返回zzzzzz
getPattern(6,'z');



我所尝试的



 字符串getPattern(int长度,字符字符){
字符串结果=;
for(int i = 0; i< length; i ++){
result + = character;
}
返回结果;
}

这是我可以做到最好的表现吗?

解决方案

您应该使用 StringBuilder ,而不是像这样连接字符。使用 StringBuilder.append()

StringBuilder会给你更好的表现。串联的问题是你每次创建一个新的String(字符串是不可变的)时,旧的字符串被复制,新的字符串被追加,旧的字符串被抛弃。在一段时间内(比如在一个大的for循环中),会有很多额外的工作会导致性能下降。

Basically given an int, I need to generate a String with the same length containing only the specified character. Related question here, but it relates to C# and it does matter what's in the String.

This question, and my answer to it are why I am asking this one. I'm not sure what's the best way to go about it performance wise.

Example

Method signature:

String getPattern(int length, char character);

Usage:

//returns "zzzzzz"
getPattern(6, 'z');

What I've tried

String getPattern(int length, char character) {
    String result = "";
    for (int i = 0; i < length; i++) {
        result += character;
    }
    return result;
}

Is this the best that I can do performance-wise?

解决方案

You should use StringBuilder instead of concatenating chars this way. Use StringBuilder.append().

StringBuilder will give you better performance. The problem with concatenation the way you are doing is each time a new String (string is immutable) is created then the old string is copied, the new string is appended, and the old String is thrown away. It's a lot of extra work that over a period of type (like in a big for loop) will cause performance degradation.

这篇关于用指定字符填充指定长度的String的最有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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