从文本文件中读取一些非常奇怪的字符串长度结果

时间:2013-10-10 11:35:06

标签: string text streamreader

我正在尝试阅读一个充满Twitter屏幕名称的文本文件,并将它们存储在数据库中。 ScreenNames不能超过15个字符,因此我的一个检查确保名称不超过15个字符。

当我尝试上传AmericanExpress时,我发现了一些非常奇怪的事情。

这是我的文本文件内容:

americanexpress
AmericanExpress‎
AMERICANEXPRESS

这是我的代码:

var names = new List<string>();
var badNames = new List<string>();

using (StreamReader reader = new StreamReader(file.InputStream, Encoding.UTF8))
{
    string line;
    while (!reader.EndOfStream)
    {
        line = reader.ReadLine();
        var name = line.ToLower().Trim();

        Debug.WriteLine(line + " " + line.Length + " " + name + " " + name.Length);
        if (name.Length > 15 || string.IsNullOrWhiteSpace(name))
        {
            badNames.Add(name);
            continue;
        }

        if (names.Contains(name))
        {
            continue;
        }

        names.Add(name);
    }
}

第一个americanexpress通过15岁以下的长度测试,第二个失败,第三个通过。当我在AmericanExpress的第二个循环中调试代码并将鼠标悬停在名称上时,这就是我得到的结果:

enter image description here enter image description here

这是Debug输出:

americanexpress 15 americanexpress 15
AmericanExpress‎ 16 americanexpress‎ 16
AMERICANEXPRESS 15 americanexpress 15

我已经计算过AmericanExpress中的角色至少10次,我很确定它只有15个角色。

有没有人知道为什么Visual Studio会告诉我americanexpress.Length = 16?

name = Regex.Replace(name,@“[^ \ u0000- \ u007F]”,string.Empty);

1 个答案:

答案 0 :(得分:2)

在s之后是一个字符,该字符不可见但计为char。 看看

name[15]    8206 '‎'

有关char 8206的信息,请参阅 http://www.fileformat.info/info/unicode/char/200e/index.htm

可能的解决方案: 只读ASCII值

var name = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(line.ToLower().Trim()));