Reputation: 310
I would like to know how I could insert dashed into various points into a string? I have a string that is 32 characters long I need dashes in various places 8-4-4-4-12
8 characters - 4characters... and so on till string is complete.
I tried REGEX but can only get it to add dashes at regular intervals
string newString = Regex.Replace(currentEPC, ".{6}", "$0-");
I am trying to parse a string as a Guid, but my string does not contain dashes, which it needs to be converted to the Guid.
Upvotes: 0
Views: 1148
Reputation: 460238
As Patrick has shown, you don't need to insert the dashes to parse the string to Guid
.
However, if you need this method anyway you can use:
public static string InsertStrings(string text, string insertString, params int[] rangeLengths)
{
var sb = new StringBuilder(text);
var indexes = new int[rangeLengths.Length];
for (int i = 0; i < indexes.Length; i++)
indexes[i] = rangeLengths[i] + indexes.ElementAtOrDefault(i-1) + insertString.Length;
for (int i = 0; i < indexes.Length; i++)
{
if(indexes[i] < sb.Length)
sb.Insert(indexes[i], insertString);
}
return sb.ToString();
}
Usage:
string guidString = "36b1dbc650c6407098247f87790144ff";
guidString = InsertStrings(guidString, "-", 8, 4, 4, 4, 12);
Upvotes: 2
Reputation: 157058
I am trying to parse a string as a Guid, but my string does not contain dashes, which it needs to be converted to the Guid.
No, it doesn't:
Guid g = Guid.Parse("084c1bfd133d403384e1c02113b52f8c");
This will parse the GUID for you. If you want to have it in a string representation with dashes:
string s = g.ToString();
Upvotes: 3