【问题标题】:Weird behavior with indexof method in c# [closed]c#中indexof方法的奇怪行为[关闭]
【发布时间】:2013-05-13 20:12:05
【问题描述】:

我有这段代码,其中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?

【问题讨论】:

  • 请展示一个完整的例子,包括你在哪里填充entities
  • 可能是因为在实体中你有tabletpc
  • @FredericoSchardong - 我只是猜测实体列表中的值拼写不同。
  • 您根本无法向我们展示实际代码:如果您是,它将在第一行打印出pencil 2,因为这是字符串中“铅笔”的第一个位置.正如其他人所说,请仔细检查 entities 中的字符串是否是您所期望的。 IndexOf() 工作得很好。
  • 什么是CultureInfo.CurrentCulture?您从“终端窗口”(cmd 窗口)复制粘贴字符,但某些字符无法写入该窗口,因此可能存在一些未显示的奇怪字符。 string.Join(",", entities[2]) 返回什么?甚至string.Join(",", entities[2].Select(ch =&gt; ((int)ch).ToString("X4")))?

标签: c# substring indexof


【解决方案1】:

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

试试类似的东西

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

其中\b 表示退格字符。

【讨论】:

  • 我使用@dlev 的建议解决了:char.IsLetterOrDigit()。不过,您发现了问题,谢谢!
【解决方案2】:

以下程序输出

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 中)说明方法输出内容的 cmets 时,我发现其中嵌入了一个 BEL 字符和一个 BS 字符:

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

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

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

【讨论】:

  • 它按预期工作,这是我的代码填充实体pastebin.com/mfnEcGBX
  • @FredericoSchardong 查看我的最新编辑;也许这是一个线索。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 2021-01-24
  • 2012-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多