【问题标题】:How to replace all special characters represented by ASCII values in a string [duplicate]如何替换字符串中由ASCII值表示的所有特殊字符[重复]
【发布时间】:2019-07-23 23:09:44
【问题描述】:

我从 API 接收到一串数据,其中所有特殊字符都表示为 ASCII 值。就速度和准确性而言,最好的检测和替换方法是什么?

源字符串:

    "Could not find 'Some User' are you sure this user is valid?"

期望的结果:

    "Could not find 'Some User' are you sure this user is valid?"

我目前正在使用字符串替换功能,但如果我必须对每个特殊字符都这样做,那看起来会非常难看。

string correctedErrorMessage = originalErrorMessage.Replace("'", "'").Replace("?","?");

【问题讨论】:

  • HttpUtility.HtmlDecode?或者WebUtility.HtmlDecode,如果它不是网络应用程序。
  • 注意:这些是 Unicode 代码点值。与 ASCII 无关。
  • 另请注意:鉴于文本是 HTML 或 XML 值,是否 API 可能会给您提供更复杂的结果,您需要更详细地处理,例如只是没有标记的文本? HTTP 响应标头 Content-Type 将提供有关意图的更多信息。考虑一下你是否有<b>Could not find 'Some User'.<b> <i>Are you sure this user is valid?</i>。检查 API 文档。

标签: c# string ascii


【解决方案1】:

你可以使用Html Encode/Decode

使用 System.Net;

    string val = "Could not find 'Some User' are you sure this user is valid?";
    string decodedString = WebUtility.HtmlDecode(val);

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 2019-10-14
    • 1970-01-01
    • 2011-05-16
    相关资源
    最近更新 更多