替换字符串中的一个单词的最后一个实例 - C# [英] Replace the last occurence of a word in a string - c#

查看:739
本文介绍了替换字符串中的一个单词的最后一个实例 - 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 是一样的我的文件夹名称。当发生这种情况我最终得到一个像这样的字符串:

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

现在它已经取代了 TnaName 的两个OCCURENCES与 feb11 。有没有办法,我只能更换这个词的最后一次出现在我的字符串?谢谢你。

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

注意: feb11 TnaName 这是从另一个进程 - 这不是一个问题

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 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天全站免登陆