1

I have the following code:

string group = "1,2,3,4,5";

And I need to find the last comma in the group (which in this case is between 4 and 5) and replace it with the word "AND". Do I need to use LINQ for this? If so, how?

Joseph
  • 502
  • 4
  • 15
  • Pedantic Note: "append" means "add to the end", so you can't "append something in the middle of something". (I'm referring to the title at the time of writing this) – Richardissimo Apr 20 '18 at 05:46

4 Answers4

4

No need to use LINQ, just use LastIndexOf

string str = "1,2,3,4,5";

int pos = str.LastIndexOf(',');
string result = str.Substring(0, pos) + " and " + str.Substring(pos + 1);
1

I believe the following will work, though you might want to add a check if group even contains a comma:

string group = "1,2,3,4,5";
int i = group.LastIndexOf(",");
string str = group.Substring(0, i) + " and " + group.Substring(i + 1);
Tim
  • 606
  • 4
  • 7
0

you can use a normal for loop for this

public static void Main(string[] args)
{
    string str = "1,2,3,4,5";

    for (int i=str.Length - 1; i>=0; i--) {
        if (str[i] == ',') {
            str = str.Substring(0, i+1) + " and " + str.Substring(i + 1);
            break;
        }
    }

    Console.WriteLine(str);
}

output of the program is

1,2,3,4, and 5
Danyal Imran
  • 2,515
  • 13
  • 21
0

Neat and clean and on point.

public static void Main(string[] args)
 {
    var res = ReplaceLastOccurrence("1,2,3,4,5", ",", " and ");
     Console.WriteLine(res);
 }
public static string ReplaceLastOccurrence(string Source, string Find, string Replace)
  {
      int place = Source.LastIndexOf(Find);   
      if(place == -1)
        return Source;
       string result = Source.Remove(place, Find.Length).Insert(place, Replace);
        return result;
  }

Fiddle Output:

1,2,3,4 and 5
DirtyBit
  • 16,613
  • 4
  • 34
  • 55