Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create a comma-separated string from items in a list

Tags:

dart

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?

like image 505
Blasanka Avatar asked May 18 '18 08:05

Blasanka


1 Answers

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);
}
like image 53
Blasanka Avatar answered Oct 09 '22 06:10

Blasanka