📅  最后修改于: 2020-11-05 04:16:54             🧑  作者: Mango
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 = "world";
String res = str1+str2;
print("The concatenated string : ${res}");
}
它将产生以下输出–
The concatenated string : Helloworld
您可以使用“ $ {}”来在字符串内插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);
}
它将产生以下输出–
The sum of 1 and 1 is 2
The sum of 2 and 2 is 4
下表中列出的属性都是只读的。
Sr.No | Property & Description |
---|---|
1 | codeUnits
Returns an unmodifiable list of the UTF-16 code units of this string. |
2 | isEmpty
Returns true if this string is empty. |
3 | Length
Returns the length of the string including space, tab and newline characters. |
dart:core库中的String类还提供了操作字符串的方法。这些方法中的一些在下面给出-
Sr.No | Methods & Description |
---|---|
1 | toLowerCase()
Converts all characters in this string to lower case. |
2 | toUpperCase()
Converts all characters in this string to upper case. |
3 | trim()
Returns the string without any leading and trailing whitespace. |
4 | compareTo()
Compares this object to another. |
5 | replaceAll()
Replaces all substrings that match the specified pattern with a given value. |
6 | split()
Splits the string at matches of the specified delimiter and returns a list of substrings. |
7 | substring()
Returns the substring of this string that extends from startIndex, inclusive, to endIndex, exclusive. |
8 | toString()
Returns a string representation of this object. |
9 | codeUnitAt()
Returns the 16-bit UTF-16 code unit at the given index. |