R Loomas R Loomas - 1 year ago 93
C# Question

String substitution in C#

I have a list of names and I loop through them to create a comma separated list in a string variable (Bob, George, Will, Terry).

I need the list to eventually look like (Bob, George, Will and Terry).

How do I find the LAST instance of the comma and replace it with the word "and"? Once I find the LAST instance, I think it's a simple matter of doing something like

string new=ori.Substring(0,start) + rep + ori.Substring(start+rep.Length);

Thoughts? Comments? Suggestions?


Answer Source

This should work for you. Added the alternative comma style as well.

var names = "Bob, George, Will, Terry";
var lastCommaPosition = names.LastIndexOf(',');
if (lastCommaPosition != -1) 
    names = names.Remove(lastCommaPosition, 1)
               //.Insert(lastComma, " and");
                 .Insert(lastCommaPosition, ", and");