I know I can append to a string but I want to be able to add a specific character after every 5 characters within the string
from this string alpha = abcdefghijklmnopqrstuvwxyz
to this string alpha = abcde-fghij-klmno-pqrst-uvwxy-z
I know I can append to a string but I want to be able to add a specific character after every 5 characters within the string
from this string alpha = abcdefghijklmnopqrstuvwxyz
to this string alpha = abcde-fghij-klmno-pqrst-uvwxy-z
Remember a string is immutable so you will need to create a new string.
Strings are IEnumerable so you should be able to run a for loop over it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string alpha = "abcdefghijklmnopqrstuvwxyz";
var builder = new StringBuilder();
int count = 0;
foreach (var c in alpha)
{
builder.Append(c);
if ((++count % 5) == 0)
{
builder.Append('-');
}
}
Console.WriteLine("Before: {0}", alpha);
alpha = builder.ToString();
Console.WriteLine("After: {0}", alpha);
}
}
}
Produces this:
Before: abcdefghijklmnopqrstuvwxyz
After: abcde-fghij-klmno-pqrst-uvwxy-z
string[] lines = Regex.Split(value, ".{5}");
string out = "";
foreach (string line in lines)
{
out += "-" + line;
}
out = out.Substring(1);
string alpha = "abcdefghijklmnopqrstuvwxyz";
string newAlpha = "";
for (int i = 5; i < alpha.Length; i += 6)
{
newAlpha = alpha.Insert(i, "-");
alpha = newAlpha;
}
You may define this extension method:
public static class StringExtenstions
{
public static string InsertCharAtDividedPosition(this string str, int count, string character)
{
var i = 0;
while (++i * count + (i - 1) < str.Length)
{
str = str.Insert((i * count + (i - 1)), character);
}
return str;
}
}
And use it like:
var str = "abcdefghijklmnopqrstuvwxyz";
str = str.InsertCharAtDividedPosition(5, "-");
Here is my solution, without overdoing it.
private static string AppendAtPosition(string baseString, int position, string character)
{
var sb = new StringBuilder(baseString);
for (int i = position; i < sb.Length; i += (position + character.Length))
sb.Insert(i, character);
return sb.ToString();
}
Console.WriteLine(AppendAtPosition("abcdefghijklmnopqrstuvwxyz", 5, "-"));