If I print values in a list, it will be like below:
main(List<String> arguments) {
List cities = ['NY', 'LA', 'Tokyo'];
String s = '';
for(var city in cities)
s += '$city, ';
print(s);//NY, LA, Tokyo,
}
But I want to separate each element in a list by comma(without for the last element).
In Java we can do it like below:
List<String> cities = Arrays.asList("NY", "LA", "Tokyo");
System.out.println(cities.stream().collect(joining(", ")));//NY, LA, Tokyo
In Dart I did it like below:
main(List<String> arguments) {
List cities = ['NY', 'LA', 'Tokyo'];
print(formatString(cities));//NY, LA, Tokyo
}
String formatString(List x) {
String formatted ='';
for(var i in x) {
formatted += '$i, ';
}
return formatted.replaceRange(formatted.length -2, formatted.length, '');
}
Is there any simpler method in Dart?
This is how I do it using join()
in List
:
main(List<String> arguments) {
List cities = ['NY', 'LA', 'Tokyo'];
String s = cities.join(', ');
print(s);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With