开发者

Delete the last instance of a certain string from a text file without changing the other instances of the string

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

Here is my problem.

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

However, I only want to delete it from the bottom (last instance) in the text file. There will always be a "M6T1" at the bottom of the text file, but it is not always the last line. It could 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 won't work here. I don't want to interfer with the other "M6T1"'s in the other location开发者_运维问答s in the text file.

Can someone please give me a solution to this problem?

Thanks


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;
}


Due to my low score, I am not allowed to comment on kevingessner's answer. So, I will add my comment here, with modification to his code -

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

This can cause an exception when index of needle = -1. That happens when the needle is not found in the string/haystack. To avoid that, I did it like this -

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


can't attach it reply yet unfortunately.

but see 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 don't want to write parameters uppercase. otherwise you might colide with properties seeing how those are usually written with upper camelcase too. this can potentially lead to quite some confusion

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜