简体   繁体   中英

How to concatenate two string in Dart?

I am new to Dart programming language and anyone help me find the best string concatenation methods available in Dart.

I only found the plus (+) operator to concatenate strings like other programming languages.

There are 3 ways to concatenate strings

String a = 'a';
String b = 'b';

var c1 = a + b; // + operator
var c2 = '$a$b'; // string interpolation
var c3 = 'a' 'b'; // string literals separated only by whitespace are concatenated automatically
var c4 = 'abcdefgh abcdefgh abcdefgh abcdefgh' 
         'abcdefgh abcdefgh abcdefgh abcdefgh';

Usually string interpolation is preferred over the + operator.

There is also StringBuffer for more complex and performant string building.

If you need looping for concatenation, I have this:

var list = ['satu','dua','tiga'];
var kontan = StringBuffer();
list.forEach((item){
    kontan.writeln(item);
});
konten = kontan.toString();

Suppose you have a Person class like.

class Person {
   String name;
   int age;

   Person({String name, int age}) {
    this.name = name;
    this.age = age;
  }
}

And you want to print the description of person.

var person = Person(name: 'Yogendra', age: 29);

Here you can concatenate string like this

 var personInfoString = '${person.name} is ${person.age} years old.';
 print(personInfoString);

Easiest way

String get fullname {
   var list = [firstName, lastName];
   list.removeWhere((v) => v == null);
   return list.join(" ");
}

The answer by Günter covers the majority of the cases of how you would concatenate two strings in Dart.

If you have an Iterable of Strings it will be easier to use writeAll as this gives you the option to specify an optional separator

final list = <String>['first','second','third'];
final sb = StringBuffer();
sb.writeAll(list, ', ');
print(sb.toString());

This will return

'first, second, third'

Let's think we have two strings

String a = 'Hello';
String b = 'World';
String output;

Now we want to concat this two strings

output = a + b;
print(output);

Hello World

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM