如何删除所有出现的 character/substring?

How to remove all occurrences of a character/substring?

我正在使用 .NET Micro Framework 4.1,据我所知,它没有实现 Regex class 或 String.Replace / String.Remove 方法意识到。

我有一个字符串定义为:

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

有没有办法从这个字符串中删除所有出现的 [esc]v?在 NetMF 中使用转义符 (0x1B) 后跟 0x76 的地方?

这有望给我留下:

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

我考虑过可能使用 String.Split() 方法,但这似乎对内存要求太高,因为代码是 运行 在小内存 NETMF 板上。

扩展?试试这个

public static string Replace(this string stringToSearch, char charToFind, char charToSubstitute)
{        
    char[] chars = stringToSearch.ToCharArray();
    for (int i = 0; i < chars.Length; i++)
        if (chars[i] == charToFind) chars[i] = charToSubstitute;

    return new string(chars);
}

使用

StringBuilder.Replace
StringBuilder.Remove 

在 .NET Micro Framework 版本 2.5、3.0、4.0 和 4.1 中 available

        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();
        } 

用法:

        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);

我最终找到了如何以另一种方式实现这一点。

不过,我首先使用了类似@Filip的回答的方法:

我用过:

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

byte [] msg = System.Text.Encoding.UTF8.GetBytes(message);
for(int i=0; i< msg.Length; i++)
{
    if (msg[i] ==0x1B || msg[i] == 0x76) msg[i] = 0x00;
}
//msg is now in byte[] format

然后我可以继续使用

将其重新转换为我的字符串
message = new string(System.Text.Encoding.UTF8.getChars(msg));

不过,对于我的项目,我可以保留 byte[] 格式。


但是,根据我的情况,(因为我是从串行端口读取的 - 没有 提到的问题,我知道没有想到这很重要 ),我能够简单地 'stop' 这些字符从一开始就输入到字符串中,使用:

if( buffer[0] !=0x1B && buffer[0] !=0x76)
{
    //add to string since it's not either
}

我能够做到这一点,因为 'wanted' 个字符都是大写的,所以 'v' 永远不会出现在消息中。


但是,如果将来有需要,如果有更好的方法 of 删除 char/substring,我仍然会感兴趣。