c# - How to replace a substring of a string


String Replace() Method



In the .net framework, we can replace a string or a substring from a specified string with another string. The String Replace(String, String) method allows us to replace a string with another string.




This method returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string. Replace method requires two parameters. Both parameters type is System.String. The first parameter's name is oldValue that the string to be replaced. And the second parameter's name is newValue where the string replaces all occurrences of the old value.




If the method does not find oldValue in the current instance then it returns the current instance unchanged. Otherwise, it replaces the string with a specified string and returns a new string.




This method performs an ordinal (case sensitive and culture insensitive) search to find oldValue.




String.Replace(Char, Char) method returns a new string in which all occurrences of a specified Unicode character in this instance are replaced with another specified Unicode character.




The following asp.net c# example code demonstrates to us how can we perform string replacement in the .net framework.





Replace.aspx



<%@ Page Language="C#" %>
<!DOCTYPE html>

<script runat="server">
protected void page_Load(object sender, System.EventArgs e) {
if(!this.IsPostBack)
{
TextBox1.Text = "This is a sample string.";
}
}
protected void Button1_Click(object sender, System.EventArgs e) {
string myString = TextBox1.Text.ToString();
string replaceString = myString.Replace("sample","test");

Label1.Text = "String replaced successfully [sample with test]!";
TextBox1.Text = replaceString;
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to replace a specified substring with another string in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Maroon">asp.net string example: Replace()</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Size="Large"
ForeColor="Red"
Font-Bold="true"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Label
ID="Label2"
runat="server"
Text="Test String"
ForeColor="DarkSlateBlue"
>
</asp:Label>
<asp:TextBox
ID="TextBox1"
runat="server"
BackColor="DarkSlateBlue"
ForeColor="AliceBlue"
>
</asp:TextBox>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Font-Bold="true"
Text="Replace sample With test"
ForeColor="DarkSlateBlue"
/>
</div>
</form>
</body>
</html>