Hello World
Hello World

Reputation: 1437

Checking for and removing any characters in a string

I am wondering what would be the best way to specify an array of characters like,

{
}
[
]

and then check a string for these and if they are there, to completely remove them.

        if (compiler.Parser.GetErrors().Count == 0)
        {
            AstNode root = compiler.Parse(phrase.ToLower());
            if (compiler.Parser.GetErrors().Count == 0)
            {
                try
                {
                    fTextSearch = SearchGrammar.ConvertQuery(root, SearchGrammar.TermType.Inflectional);
                }
                catch
                {
                    fTextSearch = phrase;
                }
            }
            else
            {
                fTextSearch = phrase;
            }
        }
        else
        {
            fTextSearch = phrase;
        }

        string[] brackets = brackets = new string[]
        {
            "{",
            "}",
            "[",
            "]"
        };

        string[] errorChars = errorChars = new string[]
        {
            "'",
            "&"
        };

        StringBuilder sb = new StringBuilder();

        string[] splitString = fTextSearch.Split(errorChars, StringSplitOptions.None);

        int numNewCharactersAdded = 0;
        foreach (string itm in splitString)
        {
            sb.Append(itm); //append string
            if (fTextSearch.Length > (sb.Length - numNewCharactersAdded))
            {
                sb.Append(fTextSearch[sb.Length - numNewCharactersAdded]); //append splitting character
                sb.Append(fTextSearch[sb.Length - numNewCharactersAdded - 1]); //append it again
                numNewCharactersAdded++;
            }
        }

        string newString = sb.ToString();

Upvotes: 0

Views: 1801

Answers (8)

Bernhard
Bernhard

Reputation: 2799

Taken from this answer: https://stackoverflow.com/a/12800424/1498669

Just use .Split() with the char[] of your desired removeables and recapture it with .Join() or .Concat()

char[] delChars = "[]{}<>()".ToCharArray();
string input = "some (crazy) string with brac[et]s in{si}de";

string output = string.Join(string.Empty, input.Split(delChars));
//or
string output = string.Concat(input.Split(delChars));

References:

https://learn.microsoft.com/en-us/dotnet/csharp/how-to/parse-strings-using-split https://learn.microsoft.com/en-us/dotnet/csharp/how-to/concatenate-multiple-strings#code-try-4

Upvotes: 0

JamieSee
JamieSee

Reputation: 13010

You can do this in a pretty compact fashion like this:

string s = "ab{c[d]}";
char[] ca = new char[] {'{', '}', '[', ']'};
Array.ForEach(ca, e => s = s.Replace(e.ToString(), ""));

Or this:

StringBuilder s = new StringBuilder("ab{c[d]}");
char[] ca = new char[] {'{', '}', '[', ']'};
Array.ForEach(ca, e => s.Replace(e.ToString(), ""));

Upvotes: 0

Servy
Servy

Reputation: 203802

string charsToRemove = @"[]{}";
string pattern = string.Format("[{0}]", Regex.Escape(charsToRemove));
var result = Regex.Replace(input, pattern, "");

The primary advantage of this over some of the other similar answers is that you aren't bothered with determining which characters need to be escaped in RegEx; you can let the library take care of that for you.

Upvotes: 0

Marco
Marco

Reputation: 57573

I don't know if I understand your problem, but you can solve your problem with this:

string toRemove = "{}[]";
string result = your_string_to_be_searched;
foreach(char c in toRemove)
    result = result.Replace(c.ToString(), "");

or with an extension method

static class Extensions
{
    public static string RemoveAll(this string src, string chars)
    {
        foreach(char c in chars)
            src= src.Replace(c.ToString(), "");
        return src;
    }
}

With this you can use string result = your_string_to_be_searched.RemoveAll("{}[]");

Upvotes: 0

oleksii
oleksii

Reputation: 35895

string str = "faslkjnro(fjrmn){ferqwe}{{";
char[] separators = new []{'[', ']','{','}' };
var sb = new StringBuilder();
foreach (var c in str)
{
    if (!separators.Contains(c))
    {
        sb.Append(c);
    }
}

return sb.ToString();

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460018

Another concise way is using Enumerable.Except to get the set difference of the Chars(assuming brackets are chars):

String newString = new String(oldString.Except(brackets).ToArray());

Upvotes: 5

Richard
Richard

Reputation: 108975

A regular expression can do this far more easily:

var result = Regex.Replace(input, @"[[\]()]", "");

Using a character set ([...]) to match anyone of the characters in it and replace with nothing. Regex.Replace will replace all matches.

Upvotes: 11

JMK
JMK

Reputation: 28059

How about this:

string myString = "a12{drr[ferr]vgb}rtg";
myString = myString.Replace("[", "").Replace("{", "").Replace("]", "").Replace("}", "");

You end up with:

a12drrferrvgbrtg

Upvotes: 0

Related Questions