syed mhamudul hasan akash syed mhamudul hasan akash - 2 years ago 115
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


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

Help me please.

Answer Source

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;
    //inputsb[18] = '+';
    inputsb.Replace(' ', '+', openParens, count);

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download