R Loomas
R Loomas

Reputation: 333

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?

Thanks, Bob

Upvotes: 3

Views: 898

Answers (5)

codechurn
codechurn

Reputation: 3970

This should do the trick for you:

var foo = "Bob, George, Will, Terry";
if (foo.Contains(",")) {
    foo = foo.Substring(0, foo.LastIndexOf(",")) + " and" + foo.Substring(foo.LastIndexOf(",")+ 1);
}

Upvotes: 1

Berkay Yaylacı
Berkay Yaylacı

Reputation: 4513

You can use Linq,

list.Select(i => i).Aggregate((i, j) => i + (list.IndexOf(j) == list.Count -1 ? " and "  :  " , ") + j);

Hope helps,

Upvotes: 1

KSib
KSib

Reputation: 911

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");
}

Console.WriteLine(names);

Upvotes: 3

Ralf Bönning
Ralf Bönning

Reputation: 15415

You can use a combination of LINQ and String.Join. This solution does not need the last index of a comma and is "more fluent" to read.

var list = new List<string> { "Bob", "George", "Will", "Terry" };
var listAsString = list.Count > 1 
        ? string.Join(", ", list.Take(list.Count - 1)) + " and " + list.Last()
        : list.First();

Upvotes: 1

I'm not sure what you wanted to do, but the following code works:

string original = "(Bob, George, Will, Terry)";
            string result = "";
            string[] splited = original.Split(',');
            for (int i = 0; i < splited.Count(); i++)
            {
                if(i == splited.Count() - 2)
                {
                    result += splited[i] + " and";
                }
                else if(i == splited.Count() - 1)
                {
                    result += splited[i];
                }
                else
                {
                    result += splited[i] + ",";
                }
            }

I Used split to split the original string in a vector so i worked with this vector to replace the last comma to the word "and".

Upvotes: 0

Related Questions