MarkCo
MarkCo

Reputation: 1222

Checking last element in string and removing c#

I have a list of strings that I am wanting to remove the , from the end of the string. I looked up online how to check to see if you are at the last index of a string and on how to remove the last index from the string. But when I do the following, it still does not seem to remove the ,.

List<string> groceryList = "apple, fruit, banana, carrots, mango";
var x = "buy "; 
var y = groceryList;

foreach (var item in y)
{
    x = x + item + ", ";
    
   if (item == y.Last()){
      x.Remove(x.Length - 1); }
}

I even tried x.Remove(x.Length - 2) thinking it would hit the , but the variable x still contains the , at the end of the string. Also I tried x.Remove(x.Last()) but it still does not remove the , after mango. So it will show mango, instead of mango.

Upvotes: 1

Views: 270

Answers (2)

Enigmativity
Enigmativity

Reputation: 117175

You're better off avoiding the dangling comma in the first place.

Try this:

List<string> groceryList = new List<string>() { "apple", "fruit", "banana", "carrots", "mango" };
string x = $"buy {String.Join(", ", groceryList)}";

That gives me buy apple, fruit, banana, carrots, mango.


If you want to build it yourself, then an for loop is the way to go:

for (int i = 0; i < groceryList.Count; i++)
{
    x += groceryList[i];
    if (i < groceryList.Count - 1)
        x += ", ";
}

Or an enumerator:

var e = groceryList.GetEnumerator();
if (e.MoveNext())
{
    while (true)
    {
        x += e.Current;
        if (e.MoveNext())
            x += ", ";
        else
            break;
    }
}

Upvotes: 1

David Oganov
David Oganov

Reputation: 1384

You have to reassign the value of the x. The following code should give you the desired result.

x = x.Remove(x.Length - 2, 2);

Upvotes: 1

Related Questions