Replace the last occurrence of a word in a string - C#

前端 未结 7 1912
星月不相逢
星月不相逢 2020-12-09 14:07

I have a problem where I need to replace the last occurrence of a word in a string.

Situation: I am given a string which is in this format:

相关标签:
7条回答
  • 2020-12-09 14:52

    Here is the function to replace the last occurrence of a string

    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;
    }
    
    • Source is the string on which you want to do the operation.
    • Find is the string that you want to replace.
    • Replace is the string that you want to replace it with.
    0 讨论(0)
  • 2020-12-09 14:53

    You have to do the replace manually:

    int i = filePath.LastIndexOf(TnaName);
    if (i >= 0)
        filePath = filePath.Substring(0, i) + filePath.Substring(i + TnaName.Length);
    
    0 讨论(0)
  • 2020-12-09 14:57

    Use string.LastIndexOf() to find the index of the last occurrence of the string and then use substring to look for your solution.

    0 讨论(0)
  • 2020-12-09 15:01
    var lastIndex = filePath.LastIndexOf(TnaName);
    
    filePath = filePath.Substring(0, lastIndex);
    
    0 讨论(0)
  • 2020-12-09 15:12

    The solution can be implemented even more simple with a single line:

     static string ReplaceLastOccurrence(string str, string toReplace, string replacement)
        {
            return Regex.Replace(str, $@"^(.*){toReplace}(.*?)$", $"$1{replacement}$2");
        }
    

    Hereby we take advantage of the greediness of the regex asterisk operator. The function is used like this:

    var s = "F:/feb11/MFrame/Templates/feb11";
    var tnaName = "feb11";
    var r = ReplaceLastOccurrence(s,tnaName, string.Empty);
    
    0 讨论(0)
  • 2020-12-09 15:13

    I don't see why Regex can't be used:

    public static string RegexReplace(this string source, string pattern, string replacement)
    {
      return Regex.Replace(source,pattern, replacement);
    }
    
    public static string ReplaceEnd(this string source, string value, string replacement)
    {
      return RegexReplace(source, $"{value}$", replacement);
    }
    
    public static string RemoveEnd(this string source, string value)
    {
      return ReplaceEnd(source, value, string.Empty);
    }
    

    Usage:

    string filePath ="F:/feb11/MFrame/Templates/feb11";
    filePath = filePath.RemoveEnd("feb11"); // F:/feb11/MFrame/Templates/
    filePath = filePath.ReplaceEnd("feb11","jan11"); // F:/feb11/MFrame/Templates/jan11
    
    0 讨论(0)
提交回复
热议问题