Home > Enterprise >  Split string to keywords in dart
Split string to keywords in dart

Time:06-16

If I have a string that says "This is a good example", is there any way to split it to the following output in dart:

This
This is
This is a
This is a good
This is a good example

CodePudding user response:

I would do it like this:

String text = "This is a good example";
List<String> split = text.split(" ");
for (var i = 0; i < split.length; i  ) {
  print(split.sublist(0, i   1).join(" "));
}

CodePudding user response:

  
  String str = "This is a good example";
  final split = str.split(" ");
  
  for (int i = 0; i < split.length; i  ) {
    String result = "";
    for (int j = 0; j < i 1; j  ) {
      result  = split[j];
      if (j < i) { 
        result  = " ";
      }
    }
    print(result);
  }

Result:

This
This is
This is a
This is a good
This is a good example

CodePudding user response:

You could do something like this (easy way):

  String myString = "This is a good example";
  List<String> output = myString.split(" ");
  String prev = "";
  output.forEach((element) {
    prev  = " "   element;
    print(prev);
  });

Output:

 This
 This is
 This is a
 This is a good
 This is a good example

If you'd like to simply split a string by word you could do it with the split() function:

String myString = "This is a good example";
List<String> output = myString.split(" ");
output.forEach((element) => print(element));

Output:

This
is
a
good
example
  • Related