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);
VulpesPosted Dec 12, 2012, 12:54 PM
Glenn PattonPosted Dec 13, 2012, 3:51 AM
Glenn
VulpesPosted Dec 12, 2012, 2:04 PM
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.
VulpesPosted Dec 12, 2012, 1:50 PM
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:
Glenn PattonPosted Dec 12, 2012, 12:59 PM
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
Vishnujeet KumarPosted Dec 12, 2012, 12:47 PM