2

I need a method that removes a list of characters from a string. I need to support properly all characters but I'm not sure I'm managing surrogate characters properly.

Is there any better way?

public static string Remove(string source, char[] oldChar)
{
    if (string.IsNullOrEmpty(source) || oldChar == null || oldChar.Length == 0)
        return source;

    for (int i = source.IndexOfAny(oldChar, 0); i != -1; i = source.IndexOfAny(oldChar, i))
        source = source.Remove(i, char.IsSurrogatePair(source, i) ? 2 : 1);

    return source;
}

Thank you

Frank

2
  • 2
    Well how do you want to support surrogate pairs? Because you can't represent a non-BMP character in a single char value anyway... perhaps your second argument should be int[]? Commented Jul 18, 2013 at 18:34
  • Please provide a sample input/output of what you expect. Commented Jul 18, 2013 at 21:09

2 Answers 2

3

The following does not deal with surrogate pairs as it is not clear from the question what you want to do. If fulfils the requirement of removing a list of characters from a string

public static string Remove(string source, char[] oldChar)
{
    return String.Join("", source.ToCharArray().Where(a => !oldChar.Contains(a)).ToArray());
}

Example:

var s = "hello world";
var c = new[] { 'l', 'o' };
Remove(s, c); //returns: he wrd
Sign up to request clarification or add additional context in comments.

Comments

0

If your goal is to remove surrogates may I suggest the following method: Char.ConvertFromUtf32(int utf32);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.