Dilee
Dilee

Reputation: 21

Add comma sequentially to string in C#

I have a string.

string str = "TTFTTFFTTTTF";

How can I break this string and add character ","?

result should be- TTF,TTF,FTT,TTF

Upvotes: 1

Views: 8165

Answers (3)

Mohit S
Mohit S

Reputation: 14044

You can use insert

Insert places one string into another. This forms a new string in your C# program. We use the string Insert method to place one string in the middle of another one—or at any other position.

Tip 1: We can insert one string at any index into another. IndexOf can return a suitable index.

Tip 2: Insert can be used to concatenate strings. But this is less efficient—concat, as with + is faster.

for(int i=3;i<=str.Length - 1;i+=4)
{
    str=str.Insert(i,",");
}

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460108

You could use String.Join after you've grouped by 3-chars:

var groups = str.Select((c, ix) => new { Char = c, Index = ix })
    .GroupBy(x => x.Index / 3)
    .Select(g => String.Concat(g.Select(x => x.Char)));
string result = string.Join(",", groups);

Since you're new to programming. That's a LINQ query so you need to add using System.Linq to the top of your code file.

  • The Select extension method creates an anonymous type containing the char and the index of each char.
  • GroupBy groups them by the result of index / 3 which is an integer division that truncates decimal places. That's why you create groups of three.
  • String.Concat creates a string from the 3 characters.
  • String.Join concatenates them and inserts a comma delimiter between each.

Upvotes: 2

Bauss
Bauss

Reputation: 2797

Here is a really simple solution using StringBuilder

    var stringBuilder = new StringBuilder();
    for (int i = 0; i < str.Length; i += 3)
    {
            stringBuilder.AppendFormat("{0},", str.Substring(i, 3));
    }
    stringBuilder.Length -= 1;
    str = stringBuilder.ToString();

I'm not sure if the following is better.

    stringBuilder.Append(str.Substring(i, 3)).Append(',');

I would suggest to avoid LINQ in this case as it will perform a lot more operations and this is a fairly simple task.

Upvotes: 0

Related Questions