从文本文件中删除某个字符串的最后一个实例,而不更改该字符串的其他实例

我有一个C#程序,我使用很多RegEx.Replace替换文本文件中的文本。

这是我的问题。

在我的文本文件中,我有一个代码,如“M6T1”。 此代码列在文本文件的许多位置。

但是,我只想从文本文件的底部(最后一个实例)中删除它。 文本文件底部总会有一个“M6T1”,但并不总是最后一行。 它可能是从底部开始的第3行,从底部开始的第5行等。

我只想摆脱“M6T1”的最后一个例子,所以RegEx.Replace在这里不起作用。 我不想干扰文本文件中其他位置的其他“M6T1”。

有人可以帮我解决这个问题吗?

谢谢

var needle = "M6T1"; var ix = str.LastIndexOf(needle); str = str.Substring(0, ix) + str.Substring(ix + needle.Length); 
 public static string ReplaceFirstOccurrence (string Source, string Find, string Replace) { int Place = Source.IndexOf(Find); string result = Source.Remove(Place, Find.Length).Insert(Place, Replace); return result; } public static string ReplaceLastOccurrence(string Source, string Find, string Replace) { int Place = Source.LastIndexOf(Find); string result = Source.Remove(Place, Find.Length).Insert(Place, Replace); return result; } 

由于我的分数很低,我不能评论kevingessner的答案。 所以,我将在这里添加我的评论,修改他的代码 –

 var needle = "M6T1"; var ix = str.LastIndexOf(needle); str = str.Substring(0, ix) + str.Substring(ix + needle.Length); 

当针的索引= -1时,这可能导致exception。 当在string / haystack中找不到针时会发生这种情况。 为了避免这种情况,我这样做了 –

 String needle = "M6T1"; int ix = str.LastIndexOf(needle); if(ix != -1){ str = str.Substring(0, ix) + str.Substring(ix + needle.Length); }else{//not found} 

不幸的是,不能附上它回复。

但请参阅http://msdn.microsoft.com/en-us/library/vstudio/ms229012%28v=vs.100%29.aspx http://msdn.microsoft.com/en-us/library/vstudio/ms229004 %28V = VS.100%29.aspx

用于命名约定。 你不想写参数大写。 否则你可能会考虑如何通常用上层camelcase写的那些属性。 这可能会导致相当混乱