简体   繁体   中英

Find last index of string in string array containing a value


In my program I have a text, which I'm splitting up into an Array of lines to modify the lines separately. For one modification I need to find the last index of a value in the text, to insert a new value in the line below.

Example:

text=["I like bananas",
      "I like apples",
      "I like cherries",
      "I like bananas",
      "I like apples"]

value: "bananas"

I already tried to use:

int pos = Array.FindIndex(text, row => row.Contains(value));
if (pos > -1)
{
 //insert line at pos
}

but this seems to return me the index of the first occurence. "lastIndexOf()" seems neither to be the right command for me as this looks for equality of the given value and the items in the array.

Am I doing something wrong or is there another command, to use in this case?

I don't get what is wrong with Array.FindLastIndex() method. It works exactly in the same way:

string value = "bananas";
string[] arr = 
{
    "I like bananas", 
    "I like apples",
    "I like cherries",
    "I like bananas",
    "I like apples"
};

Console.WriteLine(Array.FindLastIndex(arr, x => x.Contains(value)));

This code works for me and outputs "3".

If you replace your array with List<T> you'll get a nice FindLastIndex() method, which is exactly what you're looking for:

var texts = new List<string>(...);
var bananaIndex = texts.FindLastIndex(s => s.Contains("banana"));

You can use a List<T> instead of an Array . This would expose FindLastIndex() method, which will be exact for your need

With Linq you can Reverse the array.

int pos = Array.FindIndex(text.Reverse(), row => row.Contains(value));
if (pos > -1)
{
 //insert line at pos
}

Make sure you change the pos though. So it will be compatible with the actual array.Something like: pos = (text.Length-1-pos)

Link to documentation

The input is an Array. so first you have to convert it to a List()

string[] myArray= new string[]{"I like bananas",
  "I like apples",
  "I like cherries",
  "I like bananas",
  "I like apples"};
var pos = myArray.ToList().FindLastIndex(x => x.Contains("banana"));

Or you can apply

var pos =Array.FindLastIndex(myArray,x => x.Contains("banana"));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM