Hi @Anjali Agarwal , Welcome to Microsoft Q&A,
If all your characters are in the same format.
You can use the LastIndexOf
method to find the last occurrence, and then use Substring
to intercept the required part.
using System;
namespace xxx
{
internal class Program
{
static void Main(string[] args)
{
string inputString = "Nominated By Anjali Agarwal <br /><br />This is test by Anjali<br /><br />Nominated By Anonymous <br /><br />This is test by anonymous<br /><br />Nominated By Anonymous <br /><br />";
string phraseToRemove = "Nominated By";
string modifiedString = RemoveLastOccurrence(inputString, phraseToRemove);
Console.WriteLine(modifiedString);
Console.ReadLine();
}
static string RemoveLastOccurrence(string inputString, string phraseToRemove)
{
int lastOccurrenceIndex = inputString.LastIndexOf(phraseToRemove);
if (lastOccurrenceIndex != -1)
{
string modifiedString = inputString.Substring(0, lastOccurrenceIndex);
// Trim trailing newline if present
if (modifiedString.EndsWith("\n"))
{
modifiedString = modifiedString.Substring(0, modifiedString.Length - 1);
}
return modifiedString;
}
else
{
return inputString;
}
}
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.