Ad

Flutter: Split A String To All Possible Combinations For Search

- 1 answer

When dealing with a string of numbers let's say '12345', I would do something like this

String number = '12345';
List<String> listnumber = number.split("");
List<int> output = [];
for (int i = 0; i < listnumber.length; i++) {
  if (i != listnumber.length - 1) {
    output.add(int.parse(listnumber[i]));
  }
  List<String> temp = [listnumber[i]];
  for (int j = i + 1; j < listnumber.length; j++) {
    temp.add(listnumber[j]);
    output.add(int.parse(temp.join()));
  }
}
print(output.toString());

result:

[1, 12, 123, 1234, 12345, 2, 23, 234, 2345, 3, 34, 345, 4, 45] 

Perfect! that's exactly what I want. But now I can't get the same result for a string of letters. Can someone help me achieve the same result with a string such as 'abcde'. Thanks in advance

Ad

Answer

void main(){
String number = 'abcde';
List<String> listnumber = number.split("");
List<String> output = []; // int -> String
for (int i = 0; i < listnumber.length; i++) {
  if (i != listnumber.length - 1 ) {
    output.add(listnumber[i]); //
  }
  List<String> temp = [listnumber[i]];
  for (int j = i + 1; j < listnumber.length; j++) {
    temp.add(listnumber[j]); // 
    output.add((temp.join()));
  }
}
print(output.toString());
}

Output:

[a, ab, abc, abcd, abcde, b, bc, bcd, bcde, c, cd, cde, d, de]
Ad
source: stackoverflow.com
Ad