String.IndexOf()返回字符串的意外索引 [英] String.IndexOf() returns unexpected index of string

查看:157
本文介绍了String.IndexOf()返回字符串的意外索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String.IndexOf()方法的作用与我预期的不同.

String.IndexOf() method is not acting as I expected.

我希望找不到匹配的内容,因为确切的单词 you 不在str中.

I expected it not to find a match, since the exact word you is not in str.

string str = "I am your Friend";
int index = str.IndexOf("you",0,StringComparison.OrdinalIgnoreCase);
Console.WriteLine(index);

输出:5

我的预期结果为-1,因为该字符串不包含.

My Expected Result is -1 because the string doesn't contain you.

推荐答案

您面临的问题是,因为IndexOf匹配单个字符或较大字符串中的字符序列(搜索字符串).因此,我是您的朋友"包含序列您".要仅匹配单词,您必须在单词级别考虑事物.

The issue you're facing is because IndexOf matches a single character, or sequence of characters (a search string) within the greater string. Therefore "I am your friend" contains the sequence "you". To match words only, you have to consider things at a word level.

例如,您可以使用正则表达式来匹配单词边界:

For example, you could use Regular Expressions' to match around the word boundaries:

private static int IndexOfWord(string val, int startAt, string search)
{
    // escape the match expression in case it contains any characters meaningful
    // to regular expressions, and then create an expression with the \b boundary
    // characters
    var escapedMatch = string.Format(@"\b{0}\b", Regex.Escape(search));

    // create a case-sensitive regular expression object using the pattern
    var exp = new Regex(escapedMatch, RegexOptions.IgnoreCase);

    // perform the match from the start position
    var match = exp.Match(val, startAt);

    // if it's successful, return the match index
    if (match.Success)
    {
        return match.Index;
    }

    // if it's unsuccessful, return -1
    return -1;
}

// overload without startAt, for when you just want to start from the beginning
private static int IndexOfWord(string val, string search)
{
    return IndexOfWord(val, 0, search);
}

在您的示例中,您将尝试匹配\byou\b,由于边界要求,该匹配将不匹配your.

In your example you would try to match \byou\b, which because of the boundary requirements won't match your.

在线试用

有关正则表达式中单词边界的更多信息,请参见此处.

See more about word boundaries in Regular Expressions here.

这篇关于String.IndexOf()返回字符串的意外索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆