¿Hay una manera fácil de devolver una cadena repetida X número de veces?


Estoy tratando de insertar un cierto número de sangrías antes de una cadena basada en una profundidad de elementos y me pregunto si hay una manera de devolver una cadena repetida X veces. Ejemplo:

string indent = "---";
Console.WriteLine(indent.Repeat(0)); //would print nothing.
Console.WriteLine(indent.Repeat(1)); //would print "---".
Console.WriteLine(indent.Repeat(2)); //would print "------".
Console.WriteLine(indent.Repeat(3)); //would print "---------".
 235
Author: Steve Townsend, 2010-09-20

15 answers

Si solo tiene la intención de repetir el mismo carácter, puede usar el constructor de cadenas que acepta un carácter y el número de veces que lo repite new String(char c, int count).

Por ejemplo, para repetir un guión cinco veces:

string result = new String('-', 5); // -----
 425
Author: Ahmad Mageed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-20 19:21:16

Si está utilizando. NET 4.0, podría usar string.Concat junto con Enumerable.Repeat.

int N = 5; // or whatever
Console.WriteLine(string.Concat(Enumerable.Repeat(indent, N)));

De lo contrario iría con algo como La respuesta de Adán.

La razón por la que generalmente no aconsejaría usar La respuesta de Andrey es simplemente que la llamada ToArray() introduce una sobrecarga superflua que se evita con el enfoque StringBuilder sugerido por Adam. Dicho esto, al menos funciona sin requerir. NET 4.0; y es rápido y fácil (y no va a matar usted si la eficiencia no es demasiado de una preocupación).

 214
Author: Dan Tao,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:50
public static class StringExtensions
{
    public static string Repeat(this string input, int count)
    {
        if (!string.IsNullOrEmpty(input))
        {
            StringBuilder builder = new StringBuilder(input.Length * count);

            for(int i = 0; i < count; i++) builder.Append(input);

            return builder.ToString();
        }

        return string.Empty;
    }
}
 38
Author: Adam Robinson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-18 18:49:15

La solución más eficaz para string

string result = new StringBuilder().Insert(0, "---", 5).ToString();
 30
Author: c0rd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-07 12:42:28

Use Cadena.PadLeft , si la cadena deseada contiene solo un char.

public static string Indent(int count, char pad)
{
    return String.Empty.PadLeft(count, pad);
}

Crédito debido aquí

 19
Author: Steve Townsend,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-20 19:34:27

Apostaría por la respuesta de Dan Tao, pero si no estás usando. NET 4.0 puedes hacer algo así:

public static string Repeat(this string str, int count)
{
    return Enumerable.Repeat(str, count)
                     .Aggregate(
                        new StringBuilder(),
                        (sb, s) => sb.Append(s))
                     .ToString();
}
 10
Author: Thomas Levesque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-20 19:20:04

Para muchos escenarios, esta es probablemente la mejor solución:

public static class StringExtensions
{
    public static string Repeat(this string s, int n)
        => new StringBuilder(s.Length * n).Insert(0, s, n).ToString();
}

El uso es entonces:

text = "Hello World! ".Repeat(5);

Esto se basa en otras respuestas (particularmente las de @c0rd). Además de la simplicidad, tiene las siguientes características, que no todas las otras técnicas discutidas comparten:

  • Repetición de una cadena de cualquier longitud, no solo de un carácter (como solicita el OP).
  • Uso eficiente de StringBuilder mediante la preasignación de almacenamiento.
 7
Author: Bob Sammers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-14 11:54:00
        string indent = "---";
        string n = string.Concat(Enumerable.Repeat(indent, 1).ToArray());
        string n = string.Concat(Enumerable.Repeat(indent, 2).ToArray());
        string n = string.Concat(Enumerable.Repeat(indent, 3).ToArray());
 2
Author: Andrey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-20 19:08:02

Me gusta la respuesta dada. A lo largo de las líneas sames, sin embargo, es lo que he utilizado en el pasado:

"".PadLeft(3*Guión'-')

Esto cumplirá creando una sangría pero técnicamente la pregunta era repetir una cadena. Si la sangría de la cadena es algo como> -

int Indent = 2;

string[] sarray = new string[6];  //assuming max of 6 levels of indent, 0 based

for (int iter = 0; iter < 6; iter++)
{
    //using c0rd's stringbuilder concept, insert ABC as the indent characters to demonstrate any string can be used
    sarray[iter] = new StringBuilder().Insert(0, "ABC", iter).ToString();
}

Console.WriteLine(sarray[Indent] +"blah");  //now pretend to output some indented line

A todos nos encanta una solución inteligente, pero a veces simple es mejor.

 2
Author: Londo Mollari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-25 20:11:44

Me sorprendió que nadie fuera de la vieja escuela. No estoy haciendo ninguna afirmaciones sobre este código, sino solo por diversión:

public static string Repeat(this string @this, int count)
{
    var dest = new char[@this.Length * count];
    for (int i = 0; i < dest.Length; i += 1)
    {
        dest[i] = @this[i % @this.Length];
    }
    return new string(dest);
}
 1
Author: OlduwanSteve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-14 15:35:40

No estoy seguro de cómo funcionaría esto, pero es una pieza de código fácil. (Probablemente lo he hecho parecer más complicado de lo que es.)

int indentCount = 3;
string indent = "---";
string stringToBeIndented = "Blah";
// Need dummy char NOT in stringToBeIndented - vertical tab, anyone?
char dummy = '\v';
stringToBeIndented.PadLeft(stringToBeIndented.Length + indentCount, dummy).Replace(dummy.ToString(), indent);

Alternativamente, si conoce el número máximo de niveles que puede esperar, podría declarar una matriz e indexarla. Probablemente querrá hacer que este array sea estático o constante.

string[] indents = new string[4] { "", indent, indent.Replace("-", "--"), indent.Replace("-", "---"), indent.Replace("-", "----") };
output = indents[indentCount] + stringToBeIndented;      
 1
Author: B H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-28 17:16:01

No tengo suficiente representante para comentar la respuesta de Adam, pero la mejor manera de hacerlo imo es así:

public static string RepeatString(string content, int numTimes) {
        if(!string.IsNullOrEmpty(content) && numTimes > 0) {
            StringBuilder builder = new StringBuilder(content.Length * numTimes);

            for(int i = 0; i < numTimes; i++) builder.Append(content);

            return builder.ToString();
        }

        return string.Empty;
    }

Debe comprobar si numTimes es mayor que cero, de lo contrario obtendrá una excepción.

 1
Author: Gru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-05 10:43:13

Otro enfoque es considerar string como IEnumerable<char> y tener un método de extensión genérico que multiplicará los elementos de una colección por el factor especificado.

public static IEnumerable<T> Repeat<T>(this IEnumerable<T> source, int times)
{
    source = source.ToArray();
    return Enumerable.Range(0, times).SelectMany(_ => source);
}

Así que en su caso:

string indent = "---";
var f = string.Concat(indent.Repeat(0)); //.NET 4 required
//or
var g = new string(indent.Repeat(5).ToArray());
 0
Author: nawfal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-24 08:49:05

No vi esta solución. Me parece más simple para donde actualmente estoy en el desarrollo de software:

public static void PrintFigure(int shapeSize)
{
    string figure = "\\/";
    for (int loopTwo = 1; loopTwo <= shapeSize - 1; loopTwo++)
    {
        Console.Write($"{figure}");
    }
}
 0
Author: Nelly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-21 09:37:33

Puede crear un método de extensión para hacer eso!

public static class StringExtension
{
  public static string Repeat(this string str, int count)
  {
    string ret = "";

    for (var x = 0; x < count; x++)
    {
      ret += str;
    }

    return ret;
  }
}

O usando la solución @Dan Tao:

public static class StringExtension
{
  public static string Repeat(this string str, int count)
  {
    if (count == 0)
      return "";

    return string.Concat(Enumerable.Repeat(indent, N))
  }
}
 -2
Author: Zote,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-20 19:09:51