afifi
afifi

Reputation: 95

How to extract a pattern of letters from a string?

I have a String 'baseball' and I want to loop on this string and print the output like this: 'b', 'ba', 'bas', 'base', 'baseb', 'baseba', 'basebal', 'baseball'

Upvotes: 0

Views: 42

Answers (2)

lrn
lrn

Reputation: 71623

I'd create the incremental substrings. If you want to reuse the functionality, perhaps make it a synchronous generator:

Iterable<String> prefixes(String string, {int minLength = 1}) sync* {
  for (var i = minLength; i <= string.length; i++) {
    yield string.substring(0, i);
  }
}

Then you can print them as you want:

  for (var prefix in prefixes("baseball")) {
    print(prefix);
  }

Upvotes: 0

Victor Cheng
Victor Cheng

Reputation: 112

Just loop through the string and concat the letters and print the result.

            String str = "baseball";
            String output = "";
            for (var i = 0; i < str.length; i++) {
              output += str[i];
              print(output);
            }

Upvotes: 1

Related Questions