I have a string like this :
string myText = "abc def ghi 123 abc def ghi 123 abc def";
I want to replace only last abc
with empty.
Here is my code:
string pattern2 = "([abc])$";
string replacement2 = "";
Regex regEx = new Regex(pattern2);
var b = Regex.Replace(regEx.Replace(myText, replacement2), @"\s", " ");
It does not work properly, so how can it be done?
It is possible with String methods like LastIndexOf
and Substring
take a look into the following code as well as this working example
string myText = "abc def ghi 123 abc def ghi 123 abc def";
string searchStr = "abc";
int lastIndex = myText.LastIndexOf(searchStr);
if(lastIndex>=0)
myText = myText.Substring(0,lastIndex) + myText.Substring(lastIndex+searchStr.Length);
Console.WriteLine(myText);
Please note : If you want to replace abc
with any other strings then use that in between them or just use String.Format to join them like the following:
string replaceStr = "replaced";
string outputStr = String.Format("{0} {1}{2}",
myText.Substring(0,lastIndex),
replaceStr,
myText.Substring(lastIndex+searchStr.Length));
That's an easy one, How about using the Remove
method
string textToRemove = "abc";
string myText = "abc def ghi 123 abc def ghi 123 abc def";
myText = myText.Remove(myText.LastIndexOf(textToRemove), textToRemove.Length);
Console.WriteLine(myText);
Output: abc def ghi 123 abc def ghi 123 def
if you want to remove the extra space between 123 and def
just + 1 on the textToRemove.Length
.
Output: abc def ghi 123 abc def ghi 123 def
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