简体   繁体   中英

How to repeat each char in string and return new string with repeated chars?

I have tried to make an extension method that repeats each char in string eg "hello" >> "hheelllloo" "Back" >> "BBBaaaccckkk"

but the output was this Image

Code that i did:

public static void Repeat(string str , int count)
    {
        StringBuilder sb = new StringBuilder();
        char[] chars = str.ToCharArray();
        for (int i = 0  ; i < str.Length; i++)
        {
            //int o = str.IndexOf(chars[i]);
             Console.WriteLine(sb.Append(chars[i], count));
        }          
    }

Using the string indexer

using System.Text;

public static string Repeat(string str, int count)
{
  StringBuilder builder = new StringBuilder(str.Length * count);
  for ( int index = 0; index < str.Length; index++ )
    builder.Append(str[index], count);
  return builder.ToString();
}

Fiddle Snippet

Test

string str = "Back";
int count = 3;
var result = Repeat(str, count);
Console.WriteLine(result);

Output

BBBaaaccckkk

Using an extension method with the string char enumerator

static public class StringHelper
{
  static public string RepeatEachChar(this string str, int count)
  {
    StringBuilder builder = new StringBuilder(str.Length * count);
    foreach ( char c in str )
      builder.Append(c, count);
    return builder.ToString();
  }
}

Console.WriteLine("Back".RepeatEachChar(3));

Another way if you need:

static string RepeatChars(string word, int times)
    {
        string newString = null;
        int i = 0;

        foreach(var character in word)
        {
            while (i < times)
            {
                newString += character;
                i++;
            }
            i = 0;
        }

        return newString;
    }

OR

static string RepeatChars(string word, int times)
    {
        string newString = null;

        foreach(var character in word)
        {
            newString += new string(character, times);
        }

        return newString;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM