【问题标题】:How can i use IndexOf to find an exact match?如何使用 IndexOf 找到完全匹配?
【发布时间】:2015-03-19 01:14:28
【问题描述】:

我正在尝试使用 IndexOf 来查找字符串段的位置。但字符串可能如下所示:

blahblahEAPPWForms
EAPPWTextblah blah
EAPPWblah

以上示例可以按任何顺序排列,但有时我可能只是在寻找“EAPPW”本身,而它可能根本不存在。但如果“EAPPWText”或“EAPPWForms”先出现,我会得到它的索引。

【问题讨论】:

  • 所以你想要“EAPPW”的索引,如果它先出现,但“EAPPWText”如果它先出现?那么其中一个的第一个实例?
  • 正如@inquisitive_mind 所说,s.IndexOf("EAPPW"); 有什么问题?

标签: c# .net indexof


【解决方案1】:

您的问题有点令人困惑,因为它并没有真正解释您是否只想一直获取 "EAPPW" 字符串,或者如果它存在并且如果它不存在,您是否想要获取它任何以"EAPPW"开头的部分

所以,这里是如何获得两者。 假设您正在查找单词 "blah" 并且仅查找单词 "blah" 你应该能够使用正则表达式来找到它。 这个正则表达式在字符串的开头、中间、结尾搜索"blah",如果它是整个字符串。

搜索方法将返回第一次出现的索引。

x = "this is blah";
reg = /^blah$|^blah\s+|\s+blah\s+|\s+blah$/;
var location = x.search(reg);

如果你想得到“blahaaa”,如果“blah”不存在,那么你可以检查结果是否为-1,然后做indexOf。

if(location === -1)
{
   location = x.indexOf("blah");
}

【讨论】:

    【解决方案2】:

    如果您正在寻找没有其他文本的实例,这非常简单:

      //Check if it's the whole string
      if(str == "EAPPWText")
         return 0;
    
      //Check if it's in the start or end
      int nIndex = str.IndexOf("EAPPWText" + " ");
      if(nIndex >= 0)
             return nIndex;
    
      //Check if it's the LAST word
      nIndex = str.IndexOf(" " + "EAPPWText" );
      return nIndex;
    

    【讨论】:

      猜你喜欢
      • 2015-06-30
      • 2015-01-04
      • 1970-01-01
      • 2022-01-28
      • 1970-01-01
      • 2014-05-08
      • 1970-01-01
      相关资源
      最近更新 更多