C# c语言中indexof方法的怪异行为
我有这个代码,其中entities是由参数接收的列表。我尝试以任何可能的方式将实体[x]强制转换为字符串,即使它已经是字符串了。我还检查了实体[x]是否字符串始终返回trueC# c语言中indexof方法的怪异行为,c#,substring,indexof,C#,Substring,Indexof,我有这个代码,其中entities是由参数接收的列表。我尝试以任何可能的方式将实体[x]强制转换为字符串,即使它已经是字符串了。我还检查了实体[x]是否字符串始终返回true 为什么indexof为tabletc返回-1?以下程序输出 pencil 2 smartboard 11 tabletc 22 这个程序是可编译的。如果您尝试它,输出是什么 using System; using System.Collections.Generic; namespace Demo { clas
为什么indexof为tabletc返回-1?以下程序输出
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的第31-35行。尝试将它们复制/粘贴到记事本++。输入的字符串以退格字符ASCII 8开头 试试像这样的东西
"... \btabletc ...".IndexOf(entities[2])
其中\b表示退格字符。请给出一个完整的示例,包括填充实体的位置。可能是因为在实体中有tabletpc@FredericoSchardong-我只是猜测entities列表中的值的拼写不同。根本不可能向我们显示实际代码:如果是,它会为第一行打印铅笔2,因为这是铅笔在字符串中的第一个位置。正如其他人所说,仔细检查实体中的字符串是否是您期望的字符串。IndexOf很好用。什么是CultureInfo.CurrentCulture?您可以从终端窗口cmd窗口复制粘贴字符,但某些字符无法写入该窗口,因此可能存在一些不显示的奇怪字符。string.Join、、实体[2]返回什么?甚至是string.Join、、entities[2]。Selectch=>intch.ToStringX4?它按预期工作,下面是我的代码填充entities@FredericoSchardong查看我的最新编辑;也许这是个线索。我用@dlev的建议解决了这个问题:char.isleterordigit。但是,您发现了问题,谢谢!
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();
}
}
}
//this method outputs:
//3
//pencil
//smartboard
//tabletc
"... \btabletc ...".IndexOf(entities[2])