Delete the last instance of a specific line from a text file without changing other line instances

I have a C # program where I use a lot of RegEx.Replace to replace text in a text file.

Here is my problem.

In my text file I have code such as "M6T1". This code is listed in many places in a text file.

However, I want to remove it only from the bottom (last instance) in the text file. The bottom of the text file will always be "M6T1", but this is not always the last line. It can be the 3rd line from the bottom, the 5th line from the bottom, etc.

I only want to get rid of the last instance of "M6T1", so RegEx.Replace does not work here. I do not want to interfere with another "M6T1" elsewhere in the text file.

Can someone please give me a solution to this problem?

thank

+5
source share
4 answers
var needle = "M6T1";
var ix = str.LastIndexOf(needle);
str = str.Substring(0, ix) + str.Substring(ix + needle.Length);
+15
source
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;
}
+2
source

- kevingessner. , , -

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

= -1. , / . , :

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

, , .

. 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

for naming conventions. You do not want to write parameters in uppercase. otherwise, you may encounter properties by seeing how they are usually written with the upper camel body. this can potentially lead to some confusion

0
source