如果我有一个字符串,上面写着"这是一个很好的例子",有没有办法把它分割成以下的输出:
This
This is
This is a
This is a good
This is a good example
我会这样做:
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(" "));
}
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);
}
结果:
This
This is
This is a
This is a good
This is a good example
你可以这样做(简单的方法):
String myString = "This is a good example";
List<String> output = myString.split(" ");
String prev = "";
output.forEach((element) {
prev += " " + element;
print(prev);
});
输出:
This
This is
This is a
This is a good
This is a good example
如果您想简单地按单词拆分字符串,您可以使用split()
函数:
String myString = "This is a good example";
List<String> output = myString.split(" ");
output.forEach((element) => print(element));
输出:
This
is
a
good
example