替换字符串中单词的最后一次出现-C# [英] Replace the last occurrence of a word in a string - C#

查看:163
本文介绍了替换字符串中单词的最后一次出现-C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我需要替换字符串中单词的最后一次出现.

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:

string filePath ="F:/jan11/MFrame/Templates/feb11";

然后我这样替换TnaName:

filePath = filePath.Replace(TnaName, ""); // feb11 is TnaName

这可行,但是当TnaName与我的folder name相同时,我遇到了问题.当发生这种情况时,我最终得到一个像这样的字符串:

This works, but I have a problem when TnaName is the same as my folder name. When this happens I end up getting a string like this:

F:/feb11/MFrame/Templates/feb11

现在,它已用feb11替换了两次出现的TnaName.有什么方法可以只替换字符串中单词的最后一个出现?

Now it has replaced both occurrences of TnaName with feb11. Is there a way that I can replace only the last occurrence of the word in my string?

注意:feb11TnaName,它来自另一个进程-没问题.

Note: feb11 is TnaName which comes from another process - that's not a problem.

推荐答案

此处是替换字符串最后一次出现的函数

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是要对其执行操作的字符串.
  • Find是要替换的字符串.
  • Replace是您要替换为的字符串.
    • 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.
    • 这篇关于替换字符串中单词的最后一次出现-C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆