Muhammad Faisal
Muhammad Faisal

Reputation: 1054

Remove Characters from String

How do I remove a character from specific character to specific character ...

Example

 string a = " Hello ! {ssd} jksssss";

In above string i want to remove character from '{' to '}'

 output -- >  `Hello !  jksssss`

Upvotes: 1

Views: 556

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

One way without using regexp is below:

string a = " Hello ! {ssd} jksssss";
int start = a.IndexOf('{');
int end = a.IndexOf('}', start);
if (end > start && start != -1) {
    a = a.Remove(pos, end-start+1);
}

Upvotes: 4

Karl Nicoll
Karl Nicoll

Reputation: 16419

You can use the Regex class in System.Text.RegularExpressions, to do the replace. For example:

var a = " Hello ! {ssd} jksssss";
var newString = Regex myRegex = new Regex("{{.+}}", "");
myRegex.Replace(a, "");

EDIT:

If you want to match multiple occurrances of curly braces, and replace each one, use this regular expression instead:

var a = "Hello ! {ssd} jksssss {tasdas}";
Regex myRegex = new Regex("{{[^{]+}}", "");
var newString = myRegex.Replace(a, "");
// a == "Hello !  jksssss "

Upvotes: 3

Espen Burud
Espen Burud

Reputation: 1881

You can also use Regex.Replace(), if you don´t want to find the specific positions and the content between braces varies.

Upvotes: 0

moses
moses

Reputation: 51

This can be done with Regex.Replace:

string a = " Hello ! {ssd} jksssss";
string b = Regex.Replace(a, "{\w+}", "");

This won't work for "Hi {!#$#@}!", that is left as an excericse :-) Start at this MSDN page for more basic information on regular expressions in .NET.

Upvotes: 5

Related Questions