【问题标题】:Alternative to std::string in C# [duplicate]在 C# 中替代 std::string [重复]
【发布时间】:2014-03-31 15:29:59
【问题描述】:

我一直在尝试找到一个替换字符串函数,它允许我在 C# 中使用类似于 std::string 的行为。我只需要它用于我从 C++ 移植到 C# 的一些代码,其中包含 std::strings。我读过关于将字符串转换为字节数组,然后从那里解决它,尽管我无法这样做。使用示例代码执行此操作的任何可能建议?请注意以下代码是用 C++ 编写的,使用 std::strings 而不是 C# Unicode 字符串。

C++ 代码

std::string DeMangleCode(const std::string& argMangledCode) const
{
   std::string unencrypted;
   for (uint32_t temp = 0; temp < argMangledCode.size(); temp++)
   {
      unencrypted += argMangledCode[temp] ^ (434 + temp) % 255;
   }
   return unencrypted;
}

错位输入:‚‡…ƒ

输出:1305

【问题讨论】:

  • 但这不是 C++ 代码。
  • 是的,它不是,它只是努力展示我在代码方面的真正意思。正如我所提到的,只需将字符串替换为 std::string 即可获得 C++ 版本的代码。
  • 我认为您正在寻找的是Chars 方法。
  • 我的 C/C++ 非常生锈,但 IIRC std::string 谈论 char,而 char 是单字节的。在这种情况下,您应该使用byte[],而不是string
  • 我们需要准确的代码,只有这样我们才能知道什么是准确的 C# 翻译。

标签: c# c++ string type-conversion


【解决方案1】:

以下代码将为输入“‚‡…ƒ”返回“1305”。诀窍是弄清楚当字符串被破坏时使用了哪个代码页。这是代码页 1252。

static public string DeMangleCode(string argMangledCode)
{
    Encoding enc = Encoding.GetEncoding(1252);
    byte[] argMangledCodeBytes = enc.GetBytes(argMangledCode);
    List<byte> unencrypted = new List<byte>();
    for (int temp = 0; temp < argMangledCodeBytes.Length; temp++)
    {
        unencrypted.Add((byte)(argMangledCodeBytes[temp] ^ (434 + temp) % 255));
    }
    return enc.GetString(unencrypted.ToArray());
}

【讨论】:

  • 非常感谢。我对这个代码页一无所知,尽管我只是在某个时候自己尝试过。感谢您更新答案。
猜你喜欢
  • 2011-12-12
  • 1970-01-01
  • 2011-07-26
  • 2011-09-24
  • 1970-01-01
  • 2014-03-17
  • 1970-01-01
  • 2022-11-04
  • 2018-07-18
相关资源
最近更新 更多