Search code examples
c#string.net-micro-framework

How to remove all occurrences of a character/substring?


I am using the .NET Micro Framework 4.1, which does no implement the Regex class or the String.Replace / String.Remove methods as far as I'm aware.

I have a string defined as:

string message = "[esc]vI AM A STRING. [esc]vI AM A STRING AND DO LOTS OF THINGS...";

Is there a way of removing all the occurrences of [esc]v from this string? Where the escape character is used (0x1B) followed by 0x76 in NetMF?

This would hopefully leave me with:

string message = "I AM A STRING. I AM A STRING AND DO LOTS OF THINGS...";

I've thought of possibly using the String.Split() method, but this seems too memory-demanding, as the code is running on a small-memoried NETMF board.


Solution

  • Use

    StringBuilder.Replace
    StringBuilder.Remove 
    

    which are available in the .NET Micro Framework versions 2.5, 3.0, 4.0, and 4.1.

            public static string fixStr(string message, char c)
            {
              StringBuilder aStr = new StringBuilder(message);
              for (int i = 0; i < aStr.Length; i++)
              {
                if (aStr[i] == c)
                {
                    aStr.Remove(i, 1);
                }
              }
              return aStr.ToString();
            } 
    

    Usage:

            string message = "" + (char)0x1B + (char)0x76 + "I AM A STRING. " + (char)0x1B + (char)0x76 + "I AM A STRING AND DO LOTS OF THINGS...";
    
            message = fixStr(message, (char)0x76);
            message = fixStr(message, (char)0x1B);