I need to insert some spaces to a string "12345678" needs to be "12 34 56 78" I belive there is a String format option to do the serperation but I'm having no luck finding it.
Any one any ideas.
Glenn
[Up Date]
Idea I had while typing this
MessageBox.Show(SerialNumber);
for (int i = 0; i < SerialNumber.Length; i++)
{
SerialNumberNew = SerialNumber.Insert(2," ");
}
almost worked ! almost I can get the space in the first place on the string. the space is moving down the string
MessageBox.Show(SerialNumberNew);

VulpesRank #55 · 29.2K reputationPosted Dec 12, 2012, 7:54 AM EST
Vishnujeet KumarRank #1,019 · 1.9K reputationPosted Dec 12, 2012, 7:47 AM EST
Glenn PattonRank #6,159 · 275 reputationPosted Dec 12, 2012, 7:59 AM EST
string Stuff = null;
String Builder output = new StringBulider();
int ctr =2;
foreach(string subString in Stuff.split(delimeters))
{
output.AppendFormat("{0}{1}",ctr++,subString);
}
Console.WriteLine(output);
I hope!!
Glenn
VulpesRank #55 · 29.2K reputationPosted Dec 12, 2012, 8:50 AM EST
However, here's another way of doing it which doesn't involve StringBuilder but requires a combination of regular expressions and LINQ:
using System.Text.RegularExpressions;
using System.Linq;
// ...
string s = "12345678";
MatchCollection mc = Regex.Matches(s, @"\d\d"); // finds each pair of 2 digits
string[] sa = (from Match m in mc select m.Value).ToArray();
s = String.Join(" ", sa);
Console.WriteLine(s); // 12 34 56 78
EDIT
Just thought of an easier way using regular expressions on their own:
VulpesRank #55 · 29.2K reputationPosted Dec 12, 2012, 9:04 AM EST
The reason why that doesn't work is because each time you insert a space it increases the indices of the following characters by 1. However, you can avoid that by iterating backwards through the string:
This has the merit of brevity and, whilst it's not as efficient as StringBuilder (a lot of intermediate strings are being created), it should be fine for serial numbers.
Glenn PattonRank #6,159 · 275 reputationPosted Dec 12, 2012, 10:51 PM EST
Glenn