Hal
Hal

Reputation: 13

C# Replace two specific commas in a string with many commas

I am trying to change the date format in each line from commas to hyphens. The index of the comma separating the month and day day and year varies.

   lines_in_List[i] = lines_in_List[i].Insert(0, cnt + ","); // Insert Draw # in 1st column

   string one_line = lines_in_List[i];
   // 0,5,1,2012,1,10,19,16,6,36,,,
   // 1,11,5,2012,49,35,23,37,38,28,,,
   // 2,12,10,2012,8,52,53,54,47,15,,,
   //  ^-^--^ replace the ',' with a '-'.

   StringBuilder changed = new StringBuilder(one_line);
   changed[3] = '-';
   changed[5] = '-';
   changed[3] = '-';
   lines_in_List[i] = changed.ToString();
}

Upvotes: 1

Views: 341

Answers (2)

Icemanind
Icemanind

Reputation: 48686

You could also do this:

string modifiedLine = Regex.Replace(line, @"(^\d+,\d+),(\d+),(\d+)", @"$1-$2-$3")

And if you need to trim spaces at the beginning of the line, use this instead:

string modifiedLine = Regex.Replace(line, @"^[ \t]*(\d+,\d+),(\d+),(\d+)", @"$1-$2-$3")

And finally, if you want to retreive just the formatted date, use this:

string justTheDate = Regex.Replace(line, @"^[ \t]*\d+,(\d+),(\d+),(\d+).*", @"$1-$2-$3")

Upvotes: 1

Eric J.
Eric J.

Reputation: 150108

You can use the overload of IndexOf that takes an initial offset to begin searching.

http://msdn.microsoft.com/en-us/library/5xkyx09y.aspx

int idxFirstComma = line.IndexOf(',');
int idxSecondComma = line.IndexOf(',', idxFirstComma+1);
int idxThirdComma = line.IndexOf(',', idxSecondComma+1);

Use those indices to do your replacements.

To efficiently replace those characters (without creating lots of temporary string instances), check this out:

http://www.dotnetperls.com/change-characters-string

That snippet converts the string to a character array, does the replacements, and creates one new string.

Upvotes: 3

Related Questions