gpt4 book ai didi

c# - 从 C# 中的字符串中去除字节顺序标记

转载 作者:IT王子 更新时间:2023-10-29 03:56:37 26 4
gpt4 key购买 nike

在 C# 中,我有一个从 WebClient.DownloadString 获取的字符串。我已经尝试将 client.Encoding 设置为新的 UTF8Encoding(false),但这没有任何区别 - 我仍然在结果字符串的开头使用 UTF-8 的字节顺序标记结束。我需要删除它(以使用 LINQ 解析生成的 XML),并希望在内存中执行此操作。

所以我有一个以\x00EF\x00BB\x00BF 开头的字符串,如果它存在,我想删除它。现在我正在使用

if (xml.StartsWith(ByteOrderMarkUtf8))
{
xml = xml.Remove(0, ByteOrderMarkUtf8.Length);
}

但这只是感觉不对。我已经尝试了各种带有流、GetBytes 和编码的代码,但没有任何效果。谁能提供从字符串中剥离 BOM 的“正确”算法?

最佳答案

我最近遇到了 .NET 4 升级的问题,但在那之前简单的答案是

String.Trim()

在 .NET 3.5 之前删除 BOM。

但是,在 .NET 4 中,您需要稍微更改它:

String.Trim(new char[]{'\uFEFF'});

这也将摆脱字节顺序标记,尽管您可能还想删除 ZERO WIDTH SPACE (U+200B):

String.Trim(new char[]{'\uFEFF','\u200B'});

您还可以使用它来删除其他不需要的字符。

一些进一步的信息来自 String.Trim Method :

The .NET Framework 3.5 SP1 and earlier versions maintain an internal list of white-space characters that this method trims. Starting with the .NET Framework 4, the method trims all Unicode white-space characters (that is, characters that produce a true return value when they are passed to the Char.IsWhiteSpace method). Because of this change, the Trim method in the .NET Framework 3.5 SP1 and earlier versions removes two characters, ZERO WIDTH SPACE (U+200B) and ZERO WIDTH NO-BREAK SPACE (U+FEFF), that the Trim method in the .NET Framework 4 and later versions does not remove. In addition, the Trim method in the .NET Framework 3.5 SP1 and earlier versions does not trim three Unicode white-space characters: MONGOLIAN VOWEL SEPARATOR (U+180E), NARROW NO-BREAK SPACE (U+202F), and MEDIUM MATHEMATICAL SPACE (U+205F).

关于c# - 从 C# 中的字符串中去除字节顺序标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1317700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com