飞镖,颤振:范围索引

时间:2020-07-22 05:17:14

标签: list flutter dart range

如何获取按值而不是索引获得的范围的索引? 例如:

["H", "e", "l", "l", "o"].getRangeIndexes(["e", "l", "l"]);
// [1, 3]

2 个答案:

答案 0 :(得分:1)

您可以如下编写类似getRangeIndexes的函数。

void main() {
  List<String> fullStringList = ["H", "e", "l", "l", "o"];
  List<String> subStringList = ["e", "l", "l"];
  print(getRangeIndexes(fullStringList, subStringList)); //<-- prints [1, 3]
}

List<int> getRangeIndexes(List<String> fullList, List<String> subList){
  List<int> rangeIndexes;
  String fullString = fullList.join("");
  String subString = subList.join("");
  if(!fullString.contains(subString)){
    rangeIndexes = [-1, -1];            //return [-1, -1] when it does not contain the same sequence
  }
  else{
    int startIndex = fullString.indexOf(subString);
    int endIndex = startIndex + (subString.length - 1);
    rangeIndexes = [startIndex, endIndex];
  }
  return rangeIndexes;
}

答案 1 :(得分:0)

尝试

theList.indexOf(subListOfTheList.first);

获取第二个列表中第二个列表的第一个元素的索引,同样获取第二个列表中最后一个元素的索引。

theList.indexOf(subListOfTheList.last);

OR 使其成为一种方法

///gives you List of indexes of all the items in smalllist as they appear in biglist,respects the order
List<int> giveBackTheIndexes<T>(List<T> main, List<T> sub) {
  var biglist = main;
  var smalllist = sub;
  final indexes = <int>[];
  smalllist.forEach((smalllistElement) {
    var i = biglist.indexOf(smalllistElement);
    indexes.add(i);
    if(i!=-1){
      biglist[i]=null;
    }
  });
  return indexes;
}

如果值是-1​​,则大列表中不存在该项目