使用C#indexOf方法,它不起作用

问题描述

我正在使用IndexOf(),它不起作用。

代码是:

  if (sqlex.Message.IndexOf("Critical") > 0)

,并且Message确实包含单词-Critical(参见图片),但不等于true。它采用了错误的路径。

我还输入了测试代码

  int index = sqlex.Message.IndexOf("Critical"); 

并且索引= 0。

为什么?

enter image description here

解决方法

字符串中的第一个位置是0,而不是1。因此,如果您的字符串是

Critical Error - do not continue. Contact IT...

然后您搜索Critical,则0是预期的结果。

If the string is not found,the result will be -1 ...除非字符串也为空,所以请确保也进行检查。

,

如果找不到字符或字符串,则string.IndexOf方法返回-1。 0表示已找到。将您的代码更改为if(sqlex.Message.IndexOf(“ Critical”)> = 0)