这可能有点过度,但考虑到替换最后一个出现的内容是一项常见任务,我想通过使用String/StringBuilder 扩展方法的方式来解决:
public static class Extensions
{
public static StringBuilder ReplaceLastOccurenceOf (this StringBuilder sb, string thingToReplace, string replacement)
{
return sb.Replace(thingToReplace, replacement, sb.ToString().LastIndexOf(thingToReplace), thingToReplace.Length);
}
public static string ReplaceLastOccurenceOf (this string s, string thingToReplace, string replacement)
{
StringBuilder sb = new StringBuilder() ; sb.Append(s);
return sb.ReplaceLastOccurenceOf(thingToReplace, replacement).ToString();
}
}
并这样称呼它们:
using System;
using System.Text;
public class Program
{
public static void Main()
{
string[] cities = { "London", "Delhi", "Paris", "New York"};
var sbCities = new StringBuilder();
foreach (string city in cities) { sbCities.Append(city + ", ");}
sbCities.Remove(sbCities.Length-2, 2);
Console.WriteLine($"sbCities = {sbCities}");
Console.WriteLine("Cities you've visited are " + sbCities.ReplaceLastOccurenceOf("Paris", "Karachi").ReplaceLastOccurenceOf(",", " and"));
Console.WriteLine();
string stringCities = string.Join(", ", cities);
Console.WriteLine($"stringCities = {stringCities}");
Console.WriteLine("Cities you've visited are " + stringCities.ReplaceLastOccurenceOf("Paris", "Karachi").ReplaceLastOccurenceOf(",", " and"));
Console.WriteLine();
}
}
在这里查看Fiddle
== result.Length - 2
这个逻辑的? - H H?:
,写一个适当的if() {}
。 - H H