Blasanka
Blasanka

Reputation: 22427

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

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?

Upvotes: 38

Views: 33523

Answers (3)

Quick learner
Quick learner

Reputation: 11457

Update:

Using the below code can be used to generate a comma separated string

String commaSeparatedString = yourList.map((item) => item).join(', ');

Upvotes: 1

Rahul Raj
Rahul Raj

Reputation: 1493

Here the simple Solution using extension

Use this extension code, paste it globally

extension ListExtentions<T> on List<T> {
String listToString() => join(',');
}

We can use this extension simply anywhere

yourStringList.listToString();
print(yourStringList.listToString());

Detailed example given below

List citiesList = ['NY', 'LA', 'Tokyo'];
String citiesString = citiesList.listToString(); // citiesString will be NY, LA, Tokyo
print(citiesString);
output: NY, LA, Tokyo

//Simply use
print(citiesList.listToString());

Upvotes: 0

Blasanka
Blasanka

Reputation: 22427

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);
}

Upvotes: 121

Related Questions