Reputation: 95
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
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
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