I have a string called \"hello world\"
I need to replace the word \"world\" to \"csharp\"
for this I use:
string.Replace(\"World\", \"csharp\
Modified @Darky711's answer to use the passed in comparison type and match the framework replace naming and xml comments as closely as possible.
///
/// Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
///
/// The string performing the replace method.
/// The string to be replaced.
/// The string replace all occurrances of oldValue.
/// Type of the comparison.
///
public static string Replace(this string str, string oldValue, string @newValue, StringComparison comparisonType)
{
@newValue = @newValue ?? string.Empty;
if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(oldValue) || oldValue.Equals(@newValue, comparisonType))
{
return str;
}
int foundAt;
while ((foundAt = str.IndexOf(oldValue, 0, comparisonType)) != -1)
{
str = str.Remove(foundAt, oldValue.Length).Insert(foundAt, @newValue);
}
return str;
}