Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an Index of a string in a list

So what I am trying do is retrieve the index of the first item, in the list, that begins with "whatever", I am not sure how to do this.

My attempt (lol):

List<string> txtLines = new List<string>();
//Fill a List<string> with the lines from the txt file.
foreach(string str in File.ReadAllLines(fileName)) {
  txtLines.Add(str);
}
//Insert the line you want to add last under the tag 'item1'.
int index = 1;
index = txtLines.IndexOf(npcID);

Yea I know it isn't really anything, and it is wrong because it seems to be looking for an item that is equal to npcID rather than the line that begins with it.

like image 289
Simon Taylor Avatar asked May 14 '13 03:05

Simon Taylor


People also ask

How do you get the index of a string in a list?

To find the index of a character in a string, use the index() method on the string. This is the quick answer.

How do I search for indexes in a list?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error.

How do you search for a string in a list Python?

We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1. count(s) if count > 0: print(f'{s} is present in the list for {count} times.


2 Answers

If you want "StartsWith" you can use FindIndex

 int index = txtLines.FindIndex(x => x.StartsWith("whatever"));
like image 60
sa_ddam213 Avatar answered Oct 09 '22 13:10

sa_ddam213


if your txtLines is a List Type, you need to put it in a loop, after that retrieve the value

int index = 1;
foreach(string line in txtLines) {
     if(line.StartsWith(npcID)) { break; }
     index ++;
}
like image 2
dArc Avatar answered Oct 09 '22 14:10

dArc