Click here to Skip to main content
14,334,439 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hello,
I just wanted one small task in my project work.
I want to split string with ':' by every two characters. I have shows detailed example below :-
If Input string is "12345678", i looking the output is "12:34:56:78"


Thanks

Vasanth
Posted
Comments
BillWoodruff 16-Sep-14 12:16pm
   
I suggest you accept OriginalGriff's answer, rather than the one I posted.
Rate this:
Please Sign up or sign in to vote.

Solution 8

OK, since we're going down the LINQ route (see solution #7), here's a slightly more efficient method: :)
public static class ExtensionMethods
{
    public static IEnumerable<T> DelimitWith<T>(this IEnumerable<T> source, T separator, int itemsPerGroup = 1)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (itemsPerGroup < 1) throw new ArgumentOutOfRangeException("itemsPerGroup");
        return DelimitWithIterator(source, separator, itemsPerGroup);
    }

    private static IEnumerable<T> DelimitWithIterator<T>(IEnumerable<T> source, T separator, int itemsPerGroup)
    {
        int count = 0;
        foreach (T item in source)
        {
            if (count == itemsPerGroup)
            {
                yield return separator;
                count = 0;
            }
            checked
            {
                count++;
            }

            yield return item;
        }
    }
}

string source = "1234567890";
char[] resultChars = source.DelimitWith(':', 2).ToArray();
string result = new string(resultChars);
   
Comments
0x01AA 20-Nov-14 11:36am
   
cool. I just start reading about "yield return". Your solution is a good example to study it. +5.
Rate this:
Please Sign up or sign in to vote.

Solution 1

There are probably simpler and more elegant ways to do this, but...
string s = "12345678";
StringBuilder sb = new StringBuilder();
int index = 0;
foreach (char c in s)
    {
    sb.AppendFormat("{0}{1}", c, (index++ & 1) == 0 ? "" : ":");
    }
s = sb.ToString().Trim(':');

Will do it.
   
Comments
Sibeesh KV 16-Sep-14 0:32am
   
Good Info :)
vasanthkumarmk 16-Sep-14 6:25am
   
yes really.
BillWoodruff 16-Sep-14 2:07am
   
+5 I hope the students of your code (and I am one of them) will appreciate that this example is very efficient: because it uses StringBuilder, and, it does not create new strings in the process of re-building the modified string.
Basmeh Awad 16-Sep-14 3:00am
   
Hi sir, can you please help me here :(
http://www.codeproject.com/Questions/818869/Connecting-multiple-stores?arn=2
george4986 16-Sep-14 23:26pm
   
nice code my +5 ;-)
Maciej Los 20-Nov-14 8:37am
   
+5!
0x01AA 20-Nov-14 11:20am
   
good lesson. 5.
Rate this:
Please Sign up or sign in to vote.

Solution 4

For the fun of it: a slight variation on the code example provided by OriginalGriff (please vote for OriginalGriff's answer, not this one):
string str = "123456789";

//check string is even in length
if (str.Length % 2 == 1) throw new ArgumentOutOfRangeException ("String length must be even");

StringBuilder sb = new StringBuilder();

int index = 0;

foreach (char c in str)
{
    sb.Append(c);
    if ((++index % 2)  == 0) sb.Append(":");
}

str = sb.Remove(sb.Length - 1, 1).ToString();
If you really want to get fancy, and try to reduce the number of loop iterations by half:
for (int i = 1, j = 0; i < (str.Length / 2); i += 2, j+= 2)
{
    sb.Append(str[j]);
    sb.Append(str[i]);
    sb.Append(':');
}

str = sb.Remove(sb.Length - 1, 1).ToString();
Whether the "cost" of the extra StringBuilder.Appends used here "outweighs" the advantage of executing the loop half the number of times, and eliminating one boolean test: my guess is that it would be marginally faster in the context of millions of executions.
   
v2
Comments
george4986 16-Sep-14 23:26pm
   
nice code my +5 ;-)
0x01AA 20-Nov-14 11:22am
   
It solves the question. 5.
Rate this:
Please Sign up or sign in to vote.

Solution 3

try this code...

string s4 = "12345678";
int pos = 2;
int len = s4.Length + (s4.Length / 2 - 1);
while (pos < len)
{
     s4 = s4.Insert(pos, ":");
     pos = pos + 3;
}


good luck ;-)
   
Comments
george4986 16-Sep-14 6:15am
   
feel free to rate down if its not working many thanks ;-)
vasanthkumarmk 16-Sep-14 11:36am
   
Thank you so much george
george4986 16-Sep-14 23:13pm
   
u r always welcome ;-)
george4986 16-Sep-14 23:24pm
   
in my code 's4.Length/2-1' calculates the number of ':' present in the string.
so the total final length of result= current length +appended ':'.
ie for 123456 length =6+2 =8.
first we add ':' after 2 digits, then adding after 3 digits (2+ count of':').
iterations are the least here(reduced more than half i suppose). happy coding. good luck ;-)
BillWoodruff 17-Sep-14 12:20pm
   
+5 reduces iterations nicely, and works for me !
george4986 17-Sep-14 23:08pm
   
thanks Bill ;-)
Maciej Los 20-Nov-14 8:39am
   
Nice catch!
+5!
george4986 20-Nov-14 22:25pm
   
thanks Maciej Los ;-)
0x01AA 20-Nov-14 11:23am
   
It works.5.
george4986 20-Nov-14 22:25pm
   
thanks Bruno ;-)
Rate this:
Please Sign up or sign in to vote.

Solution 5

string s = "1234567890";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
    if (i < s.Length - 1)
        sb.Append(s.Substring(i, 2) + ":");
    else
        sb.Append(s.Substring(i, 1) + ":");
    i++;
}
s = sb.ToString().Trim(':');
   
Rate this:
Please Sign up or sign in to vote.

Solution 6

Hi,

let me suggest a more flexible solution.
This lets you choose the chunk size:
List<string> EvenlySplit(string text, int chunkSize)
{
    if(text.Length % chunkSize == 0)
    {
        List<string> chunkList = new List<string>();

        for (int i = 0; i < text.Length; i = i + chunkSize)
        {
            chunkList.Add(text.Substring(i, chunkSize));
        }

        return chunkList;
    }
    else
    {
        throw new Exception("Cannot split. Chunk Size Error.");
    }
}
A method for getting your special string could be:

string GenerateString(string text, string separator, int chunkSize)
{
    return string.Join(separator, EvenlySplit(text, chunkSize));
}
You are free to choose the separator as well.
e.g.
GenerateString("1234567890", ":", 2);
Happy coding,

Stephan
   
v2
Comments
TheRealSteveJudge 21-Nov-14 3:28am
   
Hi Bill,

thank you for correcting the missing <string> brackets!

Actually they existed when pasting the original source code.
But unfortunately the C# auto-formatting feature of this web page suppressed them.

Best regards,
Stephan
Rate this:
Please Sign up or sign in to vote.

Solution 7

I know, few solutions have been already posted, but i want to show alternative way, by using Linq. Last weeks i'm a fan of Linq queries.
string str = "1234567890";
var qry = from c in str.ToArray().Select((x,i)=>new{c=x, Index=i+1}).ToList()
    select new{ch = (c.Index % 2)==1 ? c.c.ToString() : c.c.ToString() + ":"};

StringBuilder sb = new StringBuilder();
foreach(var s in qry)
{
    sb.Append(s.ch.ToString());
}
Console.WriteLine(sb.ToString().Trim(':'));


Result:
12:34:56:78:90
   
Rate this:
Please Sign up or sign in to vote.

Solution 9

There are plenty of other solutions, but this question looked fun, so:
using System;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            string foo = "1234567890";
            string bar = foo.Aggregate(new { i = new int[1]{ foo.Length }, sb = new StringBuilder() },
                                       (x, c) => {
                                           int i = --x.i[0];
                                           x.sb.Append(c).Append((i > 0) && ((i & 1) == 0) ? ":" : string.Empty);
                                           return x;
                                       },
                                       x => x.sb.ToString());
            Console.WriteLine(bar);
            Console.ReadLine();
        }
    }
}

This creates only the final string from the StringBuilder (no pesky Trim() ),
and with an odd length string the grouping is "right justified" (i.e., it is the first "group" that has a single character).
I have no delusions that this is more efficient than the other solutions! ;-)
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100