Replace First and Last characters from String in C# and VB.Net

Last Reply one year ago By pandeyism

Posted one year ago

Can you give an example for replace The left character and right character of string with another character ?

You are viewing reply posted by: pandeyism one year ago.
Posted one year ago


Please refer below sample.



protected void Page_Load(object sender, EventArgs e)
    string oldchar = "TSPForums.nea";
    string outcome = ReplaceLeft(oldchar);
    string finaloutcom = ReplaceRight(outcome);
    Response.Write("<b>" + oldchar + "</b>" + " After replacing left and right characters <b>" + finaloutcom + "</b>");

public string ReplaceLeft(string oldcharacterLeft)
    string result1 = oldcharacterLeft.Replace(oldcharacterLeft.Substring(0, oldcharacterLeft.Length + 1 - oldcharacterLeft.Length), "A");
    return result1;

public string ReplaceRight(string oldchrRight)
    string result2 = oldchrRight.Replace(oldchrRight.Substring(oldchrRight.Length - 1), "t");
    return result2;


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim oldchar As String = "TSPForums.nea"
    Dim outcome As String = ReplaceLeft(oldchar)
    Dim finaloutcom As String = ReplaceRight(outcome)
    Response.Write("<b>" & oldchar & "</b>" & " After replacing left and right characters <b>" & finaloutcom & "</b>")
End Sub

Public Function ReplaceLeft(ByVal oldcharacterLeft As String) As String
    Dim result1 As String = oldcharacterLeft.Replace(oldcharacterLeft.Substring(0, oldcharacterLeft.Length + 1 - oldcharacterLeft.Length), "A")
    Return result1
End Function

Public Function ReplaceRight(ByVal oldchrRight As String) As String
    Dim result2 As String = oldchrRight.Replace(oldchrRight.Substring(oldchrRight.Length - 1), "t")
    Return result2
End Function


TSPForums.nea After replacing left and right characters