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 locations in the text file.
Can someone please give me a solution to this problem?
Thanks
Using the replace() function This function takes two parameters, first parameter is the string or text to be replaced and second parameter is the text which is replacing the first parameter. To remove the text from the string the second parameter should be given as an empty string.
rstrip. The string method rstrip removes the characters from the right side of the string that is given to it. So, we can use it to remove the last element of the string. We don't have to write more than a line of code to remove the last char from the string.
Press Ctrl + H to open the Find and Replace dialog. In the Find what box, enter one of the following combinations: To eliminate text before a given character, type the character preceded by an asterisk (*char). To remove text after a certain character, type the character followed by an asterisk (char*).
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With