加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

IndexOf C#出错

发布时间:2020-12-16 01:53:47 所属栏目:百科 来源:网络整理
导读:我显然在这里遗漏了一些东西.. 我正在编写一个函数,它返回由特定字符串分隔的子字符串数. 这是一个相当简单的功能 – public static FuncError DCount(String v1,String v2,ref Int32 result) { result = 0; if (String.IsNullOrEmpty(v1)) { return null; }
我显然在这里遗漏了一些东西..

我正在编写一个函数,它返回由特定字符串分隔的子字符串数.
这是一个相当简单的功能 –

public static FuncError DCount(String v1,String v2,ref Int32 result) {
        result = 0;
        if (String.IsNullOrEmpty(v1)) {
            return null;
        }
        if (String.IsNullOrEmpty(v2)) {
            return null;
        }

        int ct = 1;
        int ix = 0;
        int nix = 0;

        do {
            nix = v1.IndexOf(v2,ix);
            if (nix >= 0) {
                ct++;

                System.Diagnostics.Debug.Print(
string.Format("{0} found at {1} count={2} result = {3}",v2,nix,ct,v1.Substring(nix,1)));
                ix = nix + v2.Length;
            }
        } while (nix >= 0);
        result = ct;
        return null;
    }

当我使用在特定情况下用作分隔符的特殊字符调用时会出现问题.它返回了许多误报.从Debug.Print开始,第一个和最后一个参数应始终相同.

t found at 105 count=2 result = t
t found at 136 count=3 result = t
t found at 152 count=4 result = t
t found at 249 count=5 result = t
t found at 265 count=6 result = t
t found at 287 count=7 result = t
t found at 317 count=8 result = t
t found at 333 count=9 result = t
t found at 443 count=10 result = t
t found at 553 count=11 result = t
t found at 663 count=12 result = t
t found at 773 count=13 result = t
t found at 883 count=14 result = t
t found at 993 count=15 result = t

如果我将pass作为char传递它可以正常工作.
如果我使用split作为分隔符拆分字符串,则返回正确数量的元素.
至于错误识别的’t’,结果中还有其他’t’未被拾取,因此它不是字符转换问题.

困惑……

谢谢

解决方法

您可以使用 StringComparison.Ordinal来获得与文化无关的字符串匹配.

使用Lasse V. Karlsen的example:

string x = "uma thurman";
x.IndexOf("t",StringComparison.Ordinal).Dump();

将导致-1.

有关更多信息,请参见Best Practices for Using Strings in the .NET Framework.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读