I have a string array lines
of which one item may contain the value Mister
or Misses
.
var lines = "3.3. 3 - 3 88C Mister Molitor D For Ne Les Text".Split(' ');
Console.WriteLine(lines.Contains("Mister") || lines.Contains("Misses"));
returns true
. Now I want to find the index of Mister
, respectively Misses
, using
var index = lines.IndexOf("Mister");
(I didn't put the code for Misses
here for the sake of simplicity)
However, index always is -1
(despite the item's existence in the array). So I thought there must be something different to try (I even added ToLower()
, which however cannot be the reason as lines.Contains()
otherwise'd return false):
var index = lines.FindIndex(x => x.ToLower() == "mister");
But still... index = -1
. This is driving me crazy! We definitely have the array containing the item, yet I can't find the index.
The following is true
lines.Contains("Mister") || lines.Contains("Misses")
because your string literal contains the word Misses
. That being said, when you call the IndexOf
on the lines
passing as a parameter the Mister
you get -1
, because Mister
is not contained in lines
.
Assuming that you do have text with the word "Mister" in it somewhere; the following code should work:
string[] lines = "3.3. 3 - 3 88C Misses Molitor D For Ne Les Text".Split(' ');
Console.WriteLine(lines.Contains("Mister") || lines.Contains("Misses"));
var idx = Array.FindIndex(lines, l => l == "Misses");
Console.WriteLine(idx);
This code worked for me. Pos has the value of 5. containsOne is true and containsTwo is false.
var lines = "3.3. 3 - 3 88C Mister Molitor D For Ne Les Text".Split(' ');
var pos = Array.FindIndex(lines, c => c.Equals("Mister"));
var containsOne = lines.Contains("Mister") || lines.Contains("Misses");
var containsTwo = lines.Contains("Mister") && lines.Contains("Misses");
For more information on the FindIndex method have a look at this page on MSDN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.