首页 / .NET / 正文

[.NET/C#]C#应用程序中重复生成字符的方法你能想到哪些?

4374 发布于: 2018-01-24 读完约需5分钟

C#应用程序中重复生成字符的方法你能想到哪些?

问题描述

如题,C#应用程序中有哪些方式可以生成一个重复某个字符或子字符串的字符串,比如有如下的伪代码:

var charToRepeat="a";
RepeatStringBuilder(chartToRepeat,3);

要求生成的结果为3a 的字符串,即将字母 a 重复3次:aaa
在C#的开发中,你能想到哪些方式来实现呢?

方案一

使用 String的实例对象:

string tabs = new String('a', n);

封装成方法可以为:

static string Tabs(int n)
{
    return new String('a', n);
}

方案二

使用 StringBuilder:

public static string Repeat(string value, int count)
{
    return new StringBuilder(value.Length * count).Insert(0, value, count).ToString();
}

方案三

使用 Enumerable.Repeat 方法:

string.Concat(Enumerable.Repeat("a", 2));

输出:aa

或者:

string.Concat(Enumerable.Repeat("ab", 2));

输出:abab

方案四

定义一个静态扩展方法:

public static class StringExtensions
{
   public static string Repeat(this char chatToRepeat, int repeat) {

       return new string(chatToRepeat,repeat);
   }
   public  static string Repeat(this string stringToRepeat,int repeat)
   {
       var builder = new StringBuilder(repeat*stringToRepeat.Length);
       for (int i = 0; i < repeat; i++) {
           builder.Append(stringToRepeat);
       }
       return builder.ToString();
   }
}

调用方法:

//字符
Debug.WriteLine('-'.Repeat(100));
//字符串
Debug.WriteLine("Hello".Repeat(100));

方案五

使用LINQ实现循环子字符串:

public static string Repeat(this string s, int n)
{
    return new String(Enumerable.Range(0, n).SelectMany(x => s).ToArray());
}

public static string Repeat(this char c, int n)
{
    return new String(c, n);
}

方案六

使用 PadLeft 方法:

public static string Repeat(char character,int numberOfIterations)
{
    return "".PadLeft(numberOfIterations, character);
}

//调用方法
Console.WriteLine(Repeat('\t',40));

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: [.NET/C#]C#应用程序中如何将文件流保存成本地文件?

下一篇: [.NET/C#].NET程序开发中怎么使用反射通过一个类型获取对应的实例对象?

本文永久链接码友网 » [.NET/C#]C#应用程序中重复生成字符的方法你能想到哪些?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册