C# string.IndexOf() 返回意外值

标签 c# string indexof

此问题适用于 C#、.net Compact Framework 2 和 Windows CE 5 设备。

我在一个 .net DLL 中遇到了一个错误,它在非常不同的 CE 设备上使用了多年,但没有出现任何问题。突然,在一台新的Windows CE 5.0设备上,这个bug出现在如下代码中:

string s = "Print revenue receipt"; // has only single space chars 
int i = s.IndexOf("  "); // two space chars

我希望 i 为 -1,但直到今天 indexOf 突然返回 5 时,这才是正确的。

因为这种行为在使用时不会发生

int i = s.IndexOf("  ", StringComparison.Ordinal);

,我很确定这是一种基于文化的现象,但我无法识别这种新设备带来的不同。它是已知设备的基本相同版本(只是更快的 CPU 和新板)。

两种设备:

  • 运行具有相同本地化版本的 Windows CE 5.0
  • System.Environment.Version 报告“2.0.7045.0”
  • CultureInfo.CurrentUICulture 和 CultureInfo.CurrentCulture 报告“en-GB”(也使用“de-DE”测试)
  • “所有”相关的注册表项都是相同的。

新设备预装了 CF 3.5,我实验性地重命名了其 GAC 文件,所描述的行为没有变化。由于在运行时总是报告版本 2.0.7045.0,我假设这些程序集没有效果。

虽然这并不难解决,但当事情看起来如此神奇时,我无法忍受。有什么提示我遗漏了什么吗?

编辑:越来越陌生了,看截图: screenshot

还有一个: screenshot

最佳答案

我相信您已经使用顺序搜索找到了答案

    int i = s.IndexOf("  ", StringComparison.Ordinal);

您可以阅读 String Class 文档中的一小部分关于这个主题有这样的话:

String search methods, such as String.StartsWith and String.IndexOf, also can perform culture-sensitive or ordinal string comparisons. The following example illustrates the differences between ordinal and culture-sensitive comparisons using the IndexOf method. A culture-sensitive search in which the current culture is English (United States) considers the substring "oe" to match the ligature "œ". Because a soft hyphen (U+00AD) is a zero-width character, the search treats the soft hyphen as equivalent to Empty and finds a match at the beginning of the string. An ordinal search, on the other hand, does not find a match in either case.

关于C# string.IndexOf() 返回意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17363564/

相关文章:

c# - 在最后一次出现模式 C# 后提取所有字符

c# - 从字符串中获取特定数字

c - 逐行读取文件,包括多个换行符

c# - 从 List<string> 中选择带有排除项和非重复选择的随机字符串

java - 检查字符串是否包含数值和字母值

javascript - 类型错误 : Cannot read property 'indexOf' of undefined

java - 在 ArrayList 中查找字符串索引的更快方法

c# - 在 asp.net 中存储用户相关数据的最佳位置在哪里?

c# - 将日期时间存储在 azure 表存储中

javascript - 突变(["hello", "Hello"]); - 如果 Hello 等于 hello 但我的代码返回 false,则返回 true?