Najlepszy sposób na powtórzenie znaku w C#

Jaki jest najlepszy sposób na wygenerowanie ciągu \t ' s W C #

Uczę się C# i eksperymentuję z różnymi sposobami mówienia tego samego.

Tabs(uint t) jest funkcją, która zwraca string z t ilością \t ' s

Na przykład Tabs(3) zwraca "\t\t\t"

Który z tych trzech sposobów realizacji Tabs(uint numTabs) jest najlepszy?

Oczywiście to zależy od tego, co oznacza "najlepsze".

  1. Wersja LINQ to tylko dwie linie, czyli nieźle. Ale czy połączenia do powtarzania i agregowania niepotrzebnie czas / zasoby pochłaniają?

  2. Wersja StringBuilder jest bardzo jasna, ale czy klasa StringBuilder jest jakoś wolniejsza?

  3. Wersja string jest podstawowa, co oznacza, że jest łatwa do zrozumienia.

  4. Czy to nie ma znaczenia? Wszyscy są równi?

To wszystkie pytania, które pomogą mi lepiej wczuć się w C#.

private string Tabs(uint numTabs)
{
    IEnumerable<string> tabs = Enumerable.Repeat("\t", (int) numTabs);
    return (numTabs > 0) ? tabs.Aggregate((sum, next) => sum + next) : ""; 
}  

private string Tabs(uint numTabs)
{
    StringBuilder sb = new StringBuilder();
    for (uint i = 0; i < numTabs; i++)
        sb.Append("\t");

    return sb.ToString();
}  

private string Tabs(uint numTabs)
{
    string output = "";
    for (uint i = 0; i < numTabs; i++)
    {
        output += '\t';
    }
    return output; 
}
 628
Author: i3arnon, 2009-01-05

19 answers

A co z tym:

string tabs = new String('\t', n);

Gdzie n jest liczbą powtórzeń ciągu znaków.

Lub lepiej:

static string Tabs(int n)
{
    return new String('\t', n);
}
 1217
Author: CMS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-13 08:36:17

We wszystkich wersjach. NET można powtórzyć ciąg znaków w ten sposób:

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

Aby powtórzyć znak, new String('\t', count) jest najlepszym rozwiązaniem. Zobacz odpowiedź @CMS .

 104
Author: Binoj Antony,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:03:03
string.Concat(Enumerable.Repeat("ab", 2));

Zwraca

"abab"

I

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

Zwraca

" aa "

Od...

Czy istnieje wbudowana funkcja do powtarzania łańcuchów lub znaków w. net?

 102
Author: Carter Medlin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:25

Najlepszą wersją jest z pewnością użycie wbudowanego sposobu:

string Tabs(int len) { return new string('\t', len); }

Spośród innych rozwiązań, preferuj najprostsze; tylko jeśli okaże się to zbyt powolne, staraj się o bardziej wydajne rozwiązanie.

Jeśli używasz StringBuilder i znasz z góry jego wynikającą długość, to również użyj odpowiedniego konstruktora, jest to o wiele bardziej efektywne, ponieważ oznacza to, że odbywa się tylko jedna czasochłonna alokacja i brak zbędnego kopiowania danych. Nonsens: oczywiście powyższy kod jest bardziej wydajny.

 55
Author: Konrad Rudolph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-23 17:31:32

Metody Rozszerzenia:

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);
}
 42
Author: Rodrick Chapman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-07 10:35:58

A co z użyciem metody rozszerzenia?


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();
   }
}

Możesz wtedy napisać:

Debug.WriteLine('-'.Repeat(100)); // For Chars  
Debug.WriteLine("Hello".Repeat(100)); // For Strings

Zauważ, że test wydajności użycia wersji stringbuilder dla prostych znaków zamiast łańcuchów daje główną preformance penality : na moim komputerze różnica w wydajności wynosi 1: 20 między: Debugowanie.WriteLine (' -'.Repeat(1000000)) //wersja char i
Debugowanie.WriteLine (" -".Repeat (1000000)) //string version

 40
Author: Ronnie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-06-20 14:24:53

A może tak:

//Repeats a character specified number of times
public static string Repeat(char character,int numberOfIterations)
{
    return "".PadLeft(numberOfIterations, character);
}

//Call the Repeat method
Console.WriteLine(Repeat('\t',40));
 20
Author: Denys Wessels,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-07 10:35:45

Wiem, że to pytanie ma już pięć lat, ale istnieje prosty sposób na powtórzenie ciągu, który działa nawet w. Net 2.0.

Aby powtórzyć łańcuch:

string repeated = new String('+', 3).Replace("+", "Hello, ");

Zwraca

"Halo, Halo, Halo"

Aby powtórzyć łańcuch jako tablicę:

// Two line version.
string repeated = new String('+', 3).Replace("+", "Hello,");
string[] repeatedArray = repeated.Split(',');

// One line version.
string[] repeatedArray = new String('+', 3).Replace("+", "Hello,").Split(',');

Zwraca

{"Hello", "Hello"," Hello",""}

To proste.
 19
Author: ChaimG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-23 22:37:53

Powiedzmy, że chcesz powtórzyć' \t ' n wiele razy, możesz użyć;

String.Empty.PadRight(n,'\t')
 16
Author: Amin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-28 10:45:21

Twój pierwszy przykład, który używa Enumerable.Repeat:

private string Tabs(uint numTabs)
{
    IEnumerable<string> tabs = Enumerable.Repeat(
                                 "\t", (int) numTabs);
    return (numTabs > 0) ? 
            tabs.Aggregate((sum, next) => sum + next) : ""; 
} 

Można przepisać bardziej zwięźle za pomocą String.Concat:

private string Tabs(uint numTabs)
{       
    return String.Concat(Enumerable.Repeat("\t", (int) numTabs));
}
 15
Author: Ray Vega,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-05 14:22:52

Za pomocą String.Concat i Enumerable.Repeat, które będą tańsze niż za pomocą String.Join

public static Repeat(this String pattern, int count)
{
    return String.Concat(Enumerable.Repeat(pattern, count));
}
 14
Author: bradgonesurfing,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-23 07:09:24
var str = new string(Enumerable.Repeat('\t', numTabs).ToArray());
 8
Author: w.b,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-07 11:07:06

ODPOWIEDŹ naprawdę zależy od złożoności, którą chcesz. Na przykład chcę zarysować wszystkie wcięcia pionowym paskiem, więc mój ciąg wcięcia jest określony w następujący sposób:

return new string(Enumerable.Range(0, indentSize*indent).Select(
  n => n%4 == 0 ? '|' : ' ').ToArray());
 4
Author: Dmitri Nesteruk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-04-06 10:58:42

Możesz utworzyć metodę rozszerzenia

static class MyExtensions
{
    internal static string Repeat(this char c, int n)
    {
        return new string(c, n);
    }
}

Wtedy możesz użyć go w ten sposób

Console.WriteLine('\t'.Repeat(10));
 2
Author: ivan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-16 17:56:58

I jeszcze jedna metoda

new System.Text.StringBuilder().Append('\t', 100).ToString()
 1
Author: Artyom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-22 08:31:48

Bez wątpienia przyjęta odpowiedź jest najlepszym i najszybszym sposobem powtórzenia pojedynczego znaku.

ODPOWIEDŹ Binoj Anthony ' ego jest prostym i dość skutecznym sposobem na powtórzenie ciągu.

Jednakże, jeśli nie przeszkadza ci trochę więcej kodu, możesz użyć mojej techniki wypełniania tablic, aby efektywnie tworzyć te ciągi jeszcze szybciej. W moich testach porównawczych poniższy kod został wykonany w około 35% czasu StringBuilder.Wstaw kod.

public static string Repeat(this string value, int count)
{
    var values = new char[count * value.Length];
    values.Fill(value.ToCharArray());
    return new string(values);
}

public static void Fill<T>(this T[] destinationArray, params T[] value)
{
    if (destinationArray == null)
    {
        throw new ArgumentNullException("destinationArray");
    }

    if (value.Length > destinationArray.Length)
    {
        throw new ArgumentException("Length of value array must not be more than length of destination");
    }

    // set the initial array value
    Array.Copy(value, destinationArray, value.Length);

    int copyLength, nextCopyLength;

    for (copyLength = value.Length; (nextCopyLength = copyLength << 1) < destinationArray.Length; copyLength = nextCopyLength)
    {
        Array.Copy(destinationArray, 0, destinationArray, copyLength, copyLength);
    }

    Array.Copy(destinationArray, 0, destinationArray, copyLength, destinationArray.Length - copyLength);
}

Aby dowiedzieć się więcej o tym wypełnieniu tablicy technika, patrz najszybszy sposób wypełnienia tablicy z pojedynczą wartością

 1
Author: Grax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-24 21:12:56

Dla mnie jest w porządku:

public static class Utils
{
    public static string LeftZerosFormatter(int zeros, int val)
    {
        string valstr = val.ToString();

        valstr = new string('0', zeros) + valstr;

        return valstr.Substring(valstr.Length - zeros, zeros);
    }
}
 1
Author: Ángel Ibáñez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-05 11:57:14

Spróbuj tego:

  1. Dodaj Microsoft.VisualBasic reference
  2. Use: String result = Microsoft.VisualBasic.Struny.StrDup(5,"hi");
  3. Daj mi znać, jeśli ci się uda.
 0
Author: Toso Pankovski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-22 16:21:05

Choć bardzo podobny do poprzedniej sugestii, Lubię zachować to proste i zastosować następujące:

string MyFancyString = "*";
int strLength = 50;
System.Console.WriteLine(MyFancyString.PadRight(strLength, "*");

Standard. Net naprawdę,

 0
Author: Porky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-27 07:28:17