string 如何在 Dart 中连接两个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53626923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:40:02  来源:igfitidea点击:

How to concatenate two string in Dart?

stringdart

提问by ASHWIN RAJEEV

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

我是 Dart 编程语言的新手,任何人都可以帮助我找到 Dart 中可用的最佳字符串连接方法。

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

我只发现加号 (+) 运算符可以像其他编程语言一样连接字符串。

回答by Günter Z?chbauer

There are 3 ways to concatenate strings

有3种连接字符串的方法

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 StringBufferfor more complex and performant string building.

还有用于更复杂和高性能的字符串构建的StringBuffer

回答by M. Syamsul Arifin

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

回答by Baig

Easiest way

最简单的方法

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

回答by Yogendra Singh

Suppose you have a Person class like.

假设你有一个 Person 类。

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