Posts String repeat method for C#
Post
Cancel

String repeat method for C#

RepeatStringBuilderAppend the best.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//src - https://gunnarpeipman.com/csharp/string-repeat/

static string RepeatForLoop(string s, int n)
{
    var result = s;

    for (var i = 0; i < n - 1; i++)
    {
        result += s;
    }

    return result;
}        

static string RepeatPadLeft(string s, int n)
{
    return "".PadLeft(n, 'X').Replace("X", s);
}

static string RepeatReplace(string s, int n)
{
    return new String('X', n).Replace("X", s);
}

static string RepeatConcat(string s, int n)
{
    return String.Concat(Enumerable.Repeat(s, n));
}

static string RepeatStringBuilderInsert(string s, int n)
{
    return new StringBuilder(s.Length * n)
                .Insert(0, s, n)
                .ToString();
}

static string RepeatStringBuilderAppend(string s, int n)
{
    return new StringBuilder(s.Length * n)
                .AppendJoin(s, new string[n+1])
                .ToString();
}

origin - http://www.pipiscrew.com/?p=13846 string-repeat-method-for-c

This post is licensed under CC BY 4.0 by the author.
Contents

Trending Tags