Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.

OK, since we're going down the LINQ route (see solution #7), here's a slightly more efficient method: :)
C#
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);
 
Share this answer
 
Comments
[no name] 20-Nov-14 11:36am    
cool. I just start reading about "yield return". Your solution is a good example to study it. +5.
There are probably simpler and more elegant ways to do this, but...
C#
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.
 
Share this answer
 
Comments
[no name] 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 ;-)
For the fun of it: a slight variation on the code example provided by OriginalGriff (please vote for OriginalGriff's answer, not this one):
C#
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:
C#
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.
 
Share this answer
 
v2
Comments
george4986 16-Sep-14 23:26pm    
nice code my +5 ;-)
[no name] 20-Nov-14 11:22am    
It solves the question. 5.
try this code...

C#
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 ;-)
 
Share this answer
 
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 !
C#
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(':');
 
Share this answer
 
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.
C#
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
 
Share this answer
 
There are plenty of other solutions, but this question looked fun, so:
C#
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! ;-)
 
Share this answer
 
v2

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900