dart 内置数据类型 String

本文深入讲解Dart语言中字符串的创建、操作及常见方法。包括使用单引号、双引号、多行字符串、字符串插值、表达式插入、字符串比较、长度获取、判断空值、字符访问以及字符串连接和重复等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看来自官网的解释:

A Dart string is a sequence of UTF-16 code units. You can use either single or double quotes to create a string

从上面的文档中发现创建字符串可以使用单引号或者双引号 这点和JavaScript和groovy kotilin一样

例子:

var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";
var s3 = 'It\'s easy to escape the string delimiter.';
var s4 = "It's even easier to use the other delimiter.";

除此之外我们还可以使用多行,创建多行字符串的另一种方法是:使用带有单引号或双引号的三重引号

void main(){
  var s1 = '''
You can create
multi-line strings like this one.
''';
  print(s1);
}

打印结果:

You can create
multi-line strings like this one.

除了三个单引号。还可以使用三个双引号

void main(){
  var s2 = """This is also a
multi-line string.""";
  print(s2);
}

可以在前面加r   表示原始字符串

void main(){
  var s = r'In a raw string, not even \n gets special treatment.';
  print(s);
}

结果:

In a raw string, not even \n gets special treatment.

dart支持表达式

You can put the value of an expression inside a string by using ${expression}. If the expression is an identifier, you can skip the {}. To get the string corresponding to an object, Dart calls the object’s toString() method

翻译:

可以使用${expression}将表达式的值放在字符串中。如果表达式是标识符,可以跳过{}。要获得与对象对应的字符串,Dart调用对象的toString()方法

例子:

void main(){
  var s = 'string interpolation';
  print('Dart has $s, which is very handy.');
}

结果:

Dart has string interpolation, which is very handy.

这个是省略了{}

比较二个字符串相等时使用==

Note: The == operator tests whether two objects are equivalent. Two strings are equivalent if they contain the same sequence of code units

翻译:

==操作符测试两个对象是否相等。如果两个字符串包含相同的代码单元序列,则它们是等价的

 

下面介绍String一些常用的方法

官方文档:String 对象api

1:获取字符串的长度

length

2:判断是否为空

isEmpty() 还有一个isNotEmpty()判断是否不为空

对着Java中的String去学就很简单了,没什么区别,但是如果想获取字符串中的某一个字符的话 有一个简单的方法

void main(){
  String s1 = 'eeaabbbbb';
  print(s1[1]);
}

这打印出来就是e了,

最后还有一个关于字符串的操作符

Operators

operator *(int times) → String

Creates a new string by concatenating this string with itself a number of times. [...]

operator +(String other) → String

Creates a new string by concatenating this string with other[...]

operator ==(Object other) → bool

Returns true if other is a String with the same sequence of code units. [...]

override

operator [](int index) → String

Gets the character (as a single-code-unit String) at the given index[...]

 

 *号操作符 表示后面累计添加多少个以前的字符串

void main(){
  String s1 = 'pig';
  print(s1*5);
}

结果:

pigpigpigpigpig

如果s1*0的话得到的是一个空字符串

+号;链接符

==号表示赋值

[]表示获取字符串中某个字符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值