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?
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?
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);
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);
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
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;
}
1,2,3,4 and 5