-1

我有这个代码,参数在哪里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?

4

2 回答 2

1

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

尝试类似的东西

"... \btabletc ...".IndexOf(entities[2])

其中\b表示退格字符。

于 2013-05-13T20:53:47.990 回答
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++ 中。

于 2013-05-13T20:23:47.887 回答