syed mhamudul hasan akash syed mhamudul hasan akash - 3 months ago 11
ASP.NET (C#) Question

String replace in specific positioned in c#

I have a string

Classic-T50 (Black+Grey)

when i send to by query string it will show in next page

Classic-T50 (Black Grey)


so i want to add + in space in this string only within bracket() only portion.

Classic-T50 (Black+Grey).


I have tried
string.Replace(" ","+")
.But it produce

Classic-T50+(Black+Grey).


But i want string
Classic-T50 (Black+Grey).


Help me please.

Answer

Use a StringBuilder and convert back to string. StringBuilder's differ from strings in that they're mutable and noninterned. It stores data in an array, and so you can replace characters like you would in an array:

void Main()
{
    var input = "Classic-T50 (Black Grey)";
    StringBuilder inputsb = new StringBuilder(input);
    var openParens = input.IndexOf('(');
    var closeParens = input.IndexOf(')');
    var count = closeParens - openParens;
    //Console.WriteLine(input);
    //inputsb[18] = '+';
    inputsb.Replace(' ', '+', openParens, count);
    Console.WriteLine(inputsb.ToString());
}

See StringBuilder.Replace Method (Char, Char, Int32, Int32

Comments