📜  如何在Dart追加或连接字符串?

📅  最后修改于: 2021-09-02 05:48:31             🧑  作者: Mango

在Dart,可以通过四种不同的方式连接字符串:

  1. 通过使用“+”运算符
  2. 通过字符串插值
  3. 通过直接编写字符串字面量
  4. 通过Strings.join()方法。

通过’+’运算符

在Dart,我们可以使用“+”运算符来连接字符串。

示例:在Dart使用“+”运算符连接字符串。

Dart
// Main function
void main() {
    
  // Assigning values
  // to the variable
  String gfg1 = "Geeks";
  String gfg2 = "For";
    
  // Printing concated result
  // by the use of '+' operator
  print(gfg1 + gfg2 + gfg1);
}


Dart
// Main function
void main() {
    
  // Assigning values to the variable
  String gfg1 = "Geeks";
  String gfg2 = "For";
    
  // Printing concated result
  // by the use of string
  // interpolation without space
  print('$gfg1$gfg2$gfg1');
    
  // Printing concated result
  // by the use of
  // string interpolation
  // with space
  print('$gfg1 $gfg2 $gfg1');
}


Dart
// Main function
void main() { 
    
  // Printing concated
  // result without space
  print('Geeks''For''Geeks');
    
  // Printing concated
  // result with space
  print('Geeks ''For ''Geeks');
}


Dart
// Main function
void main() {  
    
  // Creating List of strings
  List gfg = ["Geeks", "For" , "Geeks"];
    
  // Joining all the elements
  // of the list and
  // converting it to String
  String geek1 = gfg.join();
    
  // Printing the
  // concated string
  print(geek1);
    
  // Joining all the elements
  // of the list and converting
  // it to String
  String geek2 = gfg.join(" ");
    
  // Printing the
  // concated string
  print(geek2);
}


输出:

GeeksForGeeks

通过字符串插值

在Dart,我们可以使用字符串插值来连接字符串。

示例:使用字符串插值在Dart连接字符串。

Dart

// Main function
void main() {
    
  // Assigning values to the variable
  String gfg1 = "Geeks";
  String gfg2 = "For";
    
  // Printing concated result
  // by the use of string
  // interpolation without space
  print('$gfg1$gfg2$gfg1');
    
  // Printing concated result
  // by the use of
  // string interpolation
  // with space
  print('$gfg1 $gfg2 $gfg1');
}

输出:

GeeksForGeeks
Geeks For Geeks

通过直接编写字符串字面量

在Dart中,我们通过直接写入和其附加在连接字符串。

示例:通过直接编写字符串字面量来连接Dart的字符串。

Dart

// Main function
void main() { 
    
  // Printing concated
  // result without space
  print('Geeks''For''Geeks');
    
  // Printing concated
  // result with space
  print('Geeks ''For ''Geeks');
}

输出:

GeeksForGeeks
Geeks For Geeks

通过 List_name .join()方法

在Dart,我们还可以将列表的元素转换为一个字符串。

list_name.join("input_string(s)");

这个input_string(s)被插入到输出字符串列表的每个元素之间。

示例:在Dart使用 list_name.join() 连接字符串。

Dart

// Main function
void main() {  
    
  // Creating List of strings
  List gfg = ["Geeks", "For" , "Geeks"];
    
  // Joining all the elements
  // of the list and
  // converting it to String
  String geek1 = gfg.join();
    
  // Printing the
  // concated string
  print(geek1);
    
  // Joining all the elements
  // of the list and converting
  // it to String
  String geek2 = gfg.join(" ");
    
  // Printing the
  // concated string
  print(geek2);
}

输出:

GeeksForGeeks
Geeks For Geeks