So erstellen Sie eine durch Kommas getrennte Zeichenfolge aus Elementen in einer Liste

Post a reply

Smilies
:) :( :oops: :chelo: :roll: :wink: :muza: :sorry: :angel: :read: *x) :clever:
View more smilies

BBCode is ON
[img] is ON
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: So erstellen Sie eine durch Kommas getrennte Zeichenfolge aus Elementen in einer Liste

by Guest » 11 Jan 2025, 07:25

Wenn ich Werte in einer Liste drucke, sieht es wie folgt aus:

Code: Select all

main(List arguments) {
List cities = ['NY', 'LA', 'Tokyo'];
String s = '';
for(var city in cities)
s += '$city, ';
print(s);//NY, LA, Tokyo,
}
Aber ich möchte jedes Element in einer Liste durch Komma trennen (ohne für das letzte Element).

In Java können wir es wie folgt machen:

Code: Select all

List cities = Arrays.asList("NY", "LA", "Tokyo");
System.out.println(cities.stream().collect(joining(", ")));//NY, LA, Tokyo
In Dart habe ich es wie folgt gemacht:

Code: Select all

main(List 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, '');
}
Gibt es eine einfachere Methode in Dart?

Top