findPattern method

List<int> findPattern({
  1. required String pattern,
})

Given a pattern returns the starting indices of all occurrences of the pattern in the String.

Example

String foo = 'abracadabra';
String fooOccs = foo.findPatterns(pattern:'abr'); // returns '[0, 7]'

Implementation

List<int> findPattern({required String pattern}) {
  if (this.isBlank) {
    return [];
  }

  // ignore: omit_local_variable_types
  List<int> occurrences = [];
  // How many times the pattern can fit the text provided
  var fitCount = (this!.length / pattern.length).truncate().toInt();

  if (fitCount > this!.length) {
    return [];
  }
  if (fitCount == 1) {
    if (this == pattern) {
      return [0];
    }
    return [];
  }

  for (var i = 0; i <= this!.length; i++) {
    if (i + pattern.length > this!.length) {
      return occurrences;
    }
    if (this!.substring(i, i + pattern.length) == pattern) {
      occurrences.add(i);
    }
  }

  return occurrences;
}