String数据类型表示字符序列, Dart字符串是UTF 16代码单元的序列,Dart中的字符串值可以使用单引号,双引号或三引号表示。单行字符串使用单引号或双引号表示。三引号用于表示多行字符串。
在Dart中表示字符串值的语法如下所示-
String variable_name='value' OR String variable_name=''value'' OR String variable_name='''line1 line2''' OR String variable_name= ''''''line1 line2''''''
以下示例说明了Dart中String数据类型的用法。
void main() { String str1='this is a single line string'; String str2="this is a single line string"; String str3='''this is a multiline line string'''; String str4="""this is a multiline line string"""; print(str1); print(str2); print(str3); print(str4); }
它将产生以下输出 -
this is a single line string this is a single line string this is a multiline line string this is a multiline line string
字符串是不可变的。但是,字符串可以进行各种操作,并且输出字符串可以存储为新值。
通过将值附加到静态字符串来创建新字符串的过程称为串联或插值,换句话说,这是将一个字符串添加到另一个字符串的过程。
运算符加号(+)是连接/插入字符串的常用机制。
void main() { String str1="hello"; String str2="Learnfk"; String res=str1+str2; print("The concatenated string : ${res}"); }
它将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/dart-programming/dart-programming-string.html
来源:LearnFk无涯教程网
The concatenated string : HelloLearnfk
您可以使用" ${}"来插入字符串中Dart表达式的值,以下示例对此进行了说明。
void main() { int n=1+1; String str1="The sum of 1 and 1 is ${n}"; print(str1); String str2="The sum of 2 and 2 is ${2+2}"; print(str2); }
它将产生以下输出-
链接:https://www.learnfk.comhttps://www.learnfk.com/dart-programming/dart-programming-string.html
来源:LearnFk无涯教程网
The sum of 1 and 1 is 2 The sum of 2 and 2 is 4
下表中列出的属性都是只读的。
Sr.No | Property & 描述 |
---|---|
1 |
codeUnits 返回此字符串的UTF-16代码单元的不可更改列表。 |
2 |
isEmpty 如果此字符串为空,则返回true。 |
3 |
Length 返回字符串的长度,包括空格,制表符和换行符。 |
dart:核心库中的String类还提供了操作字符串的方法。这些方法中的一些在下面给出-
Sr.No | Methods & 描述 |
---|---|
1 |
toLowerCase() 将此字符串中的所有字符转换为小写。 |
2 |
toUpperCase() 将此字符串中的所有字符转换为大写。 |
3 |
trim() 返回没有任何前导和尾随空格的字符串。 |
4 |
compareTo() 将此对象与另一个对象进行比较。 |
5 |
replaceAll() 将所有与指定模式匹配的子字符串替换为给定值。 |
6 |
split() 在指定分隔符的匹配项处分割字符串,并返回子字符串列表。 |
7 |
substring() 返回此字符串的子字符串,该子字符串从startIndex(包括在内)到endIndex(不包括)之间扩展。 |
8 |
toString() 返回此对象的字符串表示形式。 |
9 |
codeUnitAt() 返回给定索引的16位UTF-16代码单元。 |
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)