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 = abcdefghijklmno
I had to do something similar, trying to convert a string of numbers into a timespan by adding in :
and .
. Basically I was taking 235959999 and needing to convert it to 23:59:59.999. For me it was easy because I knew where I needed to "insert" said characters.
ts = ts.Insert(6,".");
ts = ts.Insert(4,":");
ts = ts.Insert(2,":");
Basically reassigning ts to itself with the inserted character. I worked my way from the back to front, because I was lazy and didn't want to do additional math for the other inserted characters.
You could try something similar by doing:
alpha = alpha.Insert(5,"-");
alpha = alpha.Insert(11,"-"); //add 1 to account for 1 -
alpha = alpha.Insert(17,"-"); //add 2 to account for 2 -
...
string alpha = "abcdefghijklmnopqrstuvwxyz";
string newAlpha = "";
for (int i = 5; i < alpha.Length; i += 6)
{
newAlpha = alpha.Insert(i, "-");
alpha = newAlpha;
}
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);
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, "-"));
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, "-");