I need to search in a string and replace a certain string
Ex: Search String "Add Additional String to text box". Replace "Add" with "Insert"
Output expected = "Insert Additional String to text box"
If you use string s="Add Additional String to text box".replace("Add","Insert");
Output result = "Insert Insertitional String to text box"
Have anyone got ideas to get this working to give the expected output?
Thank you!
Exact match (equality comparison): == , != As with numbers, the == operator determines if two strings are equal. If they are equal, True is returned; if they are not, False is returned. It is case-sensitive, and the same applies to comparisons by other operators and methods.
In C#, Replace() method is a string method. This method is used to replace all the specified Unicode characters or specified string from the current string object and returns a new modified string. This method can be overloaded by passing arguments to it.
You can use Regex to do this:
Extension method example:
public static class StringExtensions
{
public static string SafeReplace(this string input, string find, string replace, bool matchWholeWord)
{
string textToFind = matchWholeWord ? string.Format(@"\b{0}\b", find) : find;
return Regex.Replace(input, textToFind, replace);
}
}
Usage:
string text = "Add Additional String to text box";
string result = text.SafeReplace("Add", "Insert", true);
result: "Insert Additional String to text box"
string pattern = @"\bAdd\b";
string input = "Add Additional String to text box";
string result = Regex.Replace(input, pattern, "Insert", RegexOptions.None);
"\bAdd\b" ensures that it will match the "Add" which is not part of other words. Hope it's helpful.
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