Tolani
Tolani

Reputation: 609

Create a sequence of two letters of length 10 using Linq

I have been trying to create a sequence of two letters based on a length. I know a similar question has been asked in python Strings of two letters and fixed length but it differs slightly.

[Edit]

Example abababababa is a string sequence of a , b and fixed length 11

I came up with this quick solution but I feel there is a much smarter way to do this. The fixed length can be even or odd number. For instance,

string b =String.Concat(Enumerable.Repeat(String.Concat("a", "b"), 11));
Console.WriteLine(b.Substring(0,11));

How do I achieve this?

Upvotes: 0

Views: 107

Answers (3)

Slai
Slai

Reputation: 22896

"Best" would probably be char[] or StringBuilder with a for loop, but here are few shorter ways:

string a = new string('a', 11).Replace("aa", "ab");

string b = string.Concat(Enumerable.Range(0, 11).Select(i => "ab"[i & 1]));

string c = new StringBuilder().Insert(0, "ab", ((11 + 1) / 2)).ToString(0, 11);

Upvotes: 2

Peter Duniho
Peter Duniho

Reputation: 70701

I still am not 100% sure I understand what you're asking. However, based on what you've written so far, I'd think this would do what you want:

string Repeat(string input, int length)
{
    return new string(
        Enumerable.Range(0, length).Select(i => input[i % length]).ToArray());
}

Called like:

string result = Repeat("ab", 10);

Upvotes: 2

Yoshiaki Nakamura
Yoshiaki Nakamura

Reputation: 234

is that what you want? im confused.

string b = String.Concat(Enumerable.Repeat(String.Concat("a", "b"), 5));

Upvotes: 0

Related Questions