Home > Software engineering >  Flutter: Check contain number in list
Flutter: Check contain number in list

Time:11-08

If have the following list of strings in my Flutter application.

numList = [for (var i = 0; i < 100; i  ) i.toString().padLeft(2, "0")];

It is a list from 00 to 99.

Now I would like to create two new lists out of it.

  1. One that contains all strings containing a "0" (00,01,10,02,20...)

  2. One that contains all strings starting with "1" (10,11,12,13...)

How could I do that?

CodePudding user response:

You could do something like this

List<string> containingZero = []
List<string> startingWithOne = []
for (var numberString in numList) {
    if (numberString[0] == "1") {
        startingWithOne.append(numberString)
    }
    if (numberString.contains("0")) {
        containingZero(numberString)
    }
}

First, you iterate over all strings in the list. And within that iteration, you can check the individual characters with methods such as contains() and access individual letters just like in any list

CodePudding user response:

void main(List<String> args) {
  var numList = [for (var i = 0; i < 100; i  ) 
                  i.toString().padLeft(2, "0")];
  
  var numOfZeros=[];
  var numOfOnes=[];

// loop to check every element
for(int i=0;i<numList.length;i  ){

// check if an element contains "0"

  if(numList[i].contains("0")){

    numOfZeros.add(numList[i]);
  }
  // check if an element contains "1" in its index
  if(numList[i][0].contains(RegExp("1"))){
    numOfOnes.add(numList[i]);

  }
}



print(numOfOnes);
//print(numList[91][1]);
//print(numOfZeros);
//   print("$numList");
//   print(numZero);
//   print(numList[10]);
}
  • Related