16

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

one noa
  • 336
  • 1
  • 3
  • 9
pablosal
  • 161
  • 1
  • 1
  • 4
  • 3
    You can't append to a string, and you can't add a specific character to a string. Strings cannot be modified. You *can* create a new string based on an existing string. Seems like a subtle difference, but it can be important. – Michael Petrotta Oct 07 '10 at 08:00
  • 1
    related to http://stackoverflow.com/questions/3306568/how-do-i-set-a-character-at-an-index-in-a-string-in-c/ – Matt Ellen Oct 07 '10 at 08:19

8 Answers8

24

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
Preet Sangha
  • 61,126
  • 17
  • 134
  • 202
12

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 -
...
NocFenix
  • 631
  • 5
  • 18
11

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, "-"));
danijels
  • 4,873
  • 4
  • 23
  • 36
4
string alpha = "abcdefghijklmnopqrstuvwxyz";
string newAlpha = "";
for (int i = 5; i < alpha.Length; i += 6)
{
  newAlpha = alpha.Insert(i, "-");
  alpha = newAlpha;
}
Andrei Bularca
  • 904
  • 1
  • 11
  • 28
1

Inserting Space in emailId field after every 8 characters

public string BreakEmailId(string emailId) {
    string returnVal = string.Empty;
    if (emailId.Length > 8) {           
        for (int i = 0; i < emailId.Length; i += 8) {
            returnVal += emailId.Substring(i, 8) + " ";
        }
    }

    return returnVal;
}
Perception
  • 75,573
  • 19
  • 170
  • 185
Raj
  • 81
  • 1
  • 1
0
string[] lines = Regex.Split(value, ".{5}");  
string out = "";
foreach (string line in lines)  
{  
    out += "-" + line;
}
out = out.Substring(1);
Darth Android
  • 3,237
  • 15
  • 18
0

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, "-");
Eugene Cheverda
  • 8,128
  • 2
  • 29
  • 18
0

You can use this:

string alpha = "abcdefghijklmnopqrstuvwxyz";
int length = alpha.Length;

for (int i = length - ((length - 1) % 5 + 1); i > 0; i -= 5)
{
    alpha = alpha.Insert(i, "-");
}

Works perfectly with any string. As always, the size doesn't matter. ;)

speyck
  • 287
  • 2
  • 12