同时搞定Android和iOS的Dart语言(4):字符串类型

在Dart语言中,用String表示字符串类型,可以用单引号或双引号表示字符串的值,例如,下面声明String类型变量的代码都是正确的。

String s1 = 'hello world';
String s2 = "I love you.";
var s3 = "Who are you?";

运行使用单引号和双引号表示字符串的好处是如果字符串中包含单引号时,可以使用双引号表示字符串,如果字符串中包含双引号时,可以使用单引号表示字符串。

String ss1 = 'This is an "Apple"';             // 字符串中包含双引号
String ss2 = "I've an apple";                  // 字符串中包含单引号

不过还有一种情况,就是字符串中同时包含双引号和单引号,在这种情况下,就需要使用转义符,也就是反斜杠(\)后加双引号或单引号,代码如下:

var s1 = "It's my \"coat\"";        // 反斜杠后面加双引号,可以输出双引号
var s2 = 'It\'s my "coat"';         // 反斜杠后面加单引号,可以输出单引号

如果想连接字符串,可以直接使用加号(+),如果连接的字符串都是值,可以省略加号,代码如下:

String s1 = "I ";
String s2 = "love ";
String s3 = "you.";
var ss1 = s1 + s2 + s3;         // 连接字符串
var ss2 = "I" " love" " you.";      // 连接字符串(省略加号)

如果字符串的内容比较多,而且像保留输入的格式,可以使用3对单引号或3对双引号将字符串括起来,这样在输出时,就会保留字符串在源代码文件中的格式,包括换行和缩进。代码如下:

var s1 = '''
     hello
        world
     I love you.
  ''';
var s2 = """
       hello
        world
     I love you.
  """;

在有些情况下,我们希望保留字符串的原始内容,即使字符串中有转义符,也会按原始内容输出,要满足这种需求,需要在字符串前面加r,代码如下:

var s = r'hello\nworld';
print(s);              // 输出hello\nworld

在Dart语言中并不支持字符串与其他类型的值连接,如果要想让字符串与其他类型的值连接,通常可以使用下面2种方法之一。

  • 将其他类型的值或变量转换为字符串

  • 在字符串中使用$,将其他类型的变量嵌入到字符串中

如果嵌入字符串的是对象中的属性,而不是简单的变量,需要在$后面加一对大括号,将属性括起来,如${obj.name}。

int n = 20;
int m = 30;
// 下面代码中,将n嵌入到字符串中,将m转换为字符串,然后通过“+”进行连接
var value = "n = $n, bitLength = ${n.bitLength} m = " + m.toString();
print(value);

本例演示了内建字符串类型更详细的用法。

void main() {
  var s1 = 'hello world';
  var s2 = "I love you.";
  var s3 = "It's your coat.";
  var s4 = 'This is your "coat"';
  print(s3);
  print(s4);
  var s5 = "It's my \"coat\"";
  print(s5);


  // 字符串连接
  var s6 = s1 + s2 + s3 ;
  print(s6);
  var s7 = "hello"  "world";
  print(s7);


  // 多行字符串
  var s8 = '''
     hello
        world
     I love you.
  ''';
  var s9 = """
       hello
        world
     I love you.
  """;
  print(s8);
  print(s9);


  // 原始格式的字符串
  var s10 = r'hello\nworld'; // raw string
  print(s10);


  const n1 = 50;
  const n2 = 30;
  var sum = n1 + n2;
  var mul = n1 * n2;
  // 将变量嵌入字符串
  var value = "$n1 + $n2 = $sum\n$n1 * $n2 = $mul";
  print(value);
}

运行结果如图1所示。

图1  字符串类型用法演示

对本文感兴趣,可以加李宁老师微信公众号(unitymarvel):

关注  极客起源  公众号,获得更多免费技术视频和文章。

猜你喜欢

转载自blog.csdn.net/nokiaguy/article/details/107995289