c#中indexof方法的奇怪行为

时间:2013-05-13 20:12:05

标签: c# substring indexof

我有这段代码,其中entities是参数收到的List <String>。我试图以任何可能的方式将entities[x]转换为字符串,即使它已经是一个字符串。我还检查entities[x] is String始终返回true

for(int x = 0; x < entities.Count; x++)
{
    Console.WriteLine(entities[x] + " " +  "a pencil g smartboard tabletc pencil ".IndexOf(entities[x]));
}

结果是:

pencil 30
smartboard 11
tabletc -1

为什么indexof为“tabletc”返回-1?

2 个答案:

答案 0 :(得分:1)

输入中的字符串以退格字符ASCII 8开头。

尝试类似

的内容
"... \btabletc ...".IndexOf(entities[2])

其中\b表示退格符。

答案 1 :(得分:0)

以下程序输出

pencil 2
smartboard 11
tabletc 22

此程序可编译。如果你尝试它的输出是什么?

using System;
using System.Collections.Generic;

namespace Demo
{
    class Program
    {
        void test()
        {
            var entities = new List<string> { "pencil", "smartboard", "tabletc" };

            for (int x = 0; x < entities.Count; x++)
                Console.WriteLine(entities[x] + " " +  "a pencil g smartboard tabletc pencil ".IndexOf(entities[x]));
        }

        static void Main()
        {
            new Program().test();
        }
    }
}

如果按预期工作,则下一步是查看输入的不同之处。


[编辑]

我查看了你的pastebin代码,我用我创建的测试文件尝试了它,它运行正常。然而,当我复制并粘贴(来自pastebin)表示该方法输出的注释时,我发现其中嵌入了一个BEL字符和一个BS字符:

    //this method outputs:
    //3
   //pencil
    //smartboard
   //tabletc

您无法在那里看到这些字符,但如果您将文本复制/粘贴到Notepad ++中,它们就会显示出来。它看起来很可疑,因为它们可能已从文件中读取并且是字符串的一部分,但它们不会显示出来。但它们会影响字符串匹配。

当我将这些字符粘贴在SO上时,这些字符已被剥离,但是它们存在于pastebin,第31 - 35行。尝试将它们复制/粘贴到Notepad ++中。

相关问题