在文本字符串中查找®

本文关键字:查找 字符串 文本 | 更新日期: 2023-09-27 18:32:43

让我改写一下我的问题:

我正在阅读文本,其中一个字符是注册的符号,®从显示符号没有问题的文本文件中读取。当我从文件中读取字符串后尝试打印字符串时,该符号是不可打印的字符。当我读取字符串并将字符串拆分为字符并将字符转换为 Int16 并打印出十六进制时,我得到了0xFFFD。我指定Encoding.UTF8当我打开StreamReader.

这是我所拥有的

using (System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath("~/App_Code/Hormel") + "/nutrition_data.txt", System.Text.Encoding.UTF8))
{
    string line;
    while((line = sr.ReadLine()) != null)
    {
        //after spliting the file on '~'
        items[i] = scrubData(utf8.GetString(utf8.GetBytes(items[i].ToCharArray())));
        //items[i] = scrubData(items[i]); //original
    }
}

这是 scrubData 函数

private String scrubData(string data)
        {
            string newStr = String.Empty;
            try
            {
                if (data.Contains("HORMEL"))
                {
                    string[] s = data.Split(' ');
                    foreach(string str in s)
                    {
                        if (str.Contains("HORMEL"))
                        {
                            char[] ch = str.ToCharArray();                            
                            for(int i=0; i<ch.Length; i++)
                            {
                                EventLogProvider.LogInformation("LoadNutritionInfoTask", "Test", ch[i] + " = " + String.Format("{0:X}", Convert.ToInt16(ch[i])));
                            }
                        }
                    }
                }
return String.Empty;
            }
            catch (Exception ex)
            {
                EventLogProvider.LogInformation("LoadNutritionInfoTask", "ScrubData", ex.Message);
                return data;
            }
        }

我不关心现在返回的内容,我正在打印出字符和与之对应的十六进制代码。

在文本字符串中查找®

首先,您需要确保使用正确的编码阅读文本。在我看来,您使用的是 UTF-8,因为您说®(Unicode 代码点 U+00AE)是 0xC2AE ,这与 UTF-8 相同。您可以像这样使用它:

Encoding.UTF8.GetString(new byte[] { 0xc2, 0xae }) // "®", the registered symbol
// or
using (var streamReader = new StreamReader(file, Encoding.UTF8))

在 C# 中将其作为string后,应使用 HttpUtility.HtmlEncode 将其编码为 HTML。 例如

HttpUtility.HtmlEncode("SomeStuff®") // result is "SomeStuff&#174;"

检查您正在解码字节的编码。

试试这个:

        string txt = "textwithsymbol";
        string html = "<html></html>";
        txt = txt.Replace("'u00ae", html);

显然,您会将 txt 变量替换为您读过的文本,"''u00ae"是您正在寻找的符号。