Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 837
jbutler483 Avatar asked Jan 15 '15 13:01

jbutler483


1 Answers

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);
like image 83
Eric Bole-Feysot Avatar answered Sep 22 '22 19:09

Eric Bole-Feysot