Dart语言-String
Dart中的String是一个不可变的Unicode字符串。它是Dart中最基本的数据类型之一。在本文中,我们将讨论Dart中String的一些常见操作和用法。
创建String
在Dart中创建String有几种不同的方法。最常见的方法是使用字面量,即将字符串文本放在引号(单引号或双引号)中。例如:
String str1 = 'Hello world'; //单引号
String str2 = "Hello world"; //双引号
Dart还支持使用三个引号来创建多行字符串:
String str3 = '''
This is a
multi-line
string
''';
还可以使用String构造函数来创建字符串:
String str4 = String.fromCharCode(65);
在这个例子中,我们使用fromCharCode()方法将ASCII代码65转换为字符“A”。
String长度
要获取一个String的长度,可以使用length属性:
String str = 'Hello world';
print(str.length); //输出11
String连接
Dart中的字符串可以连接,可以使用+运算符连接两个或多个字符串:
String str1 = 'Hello';
String str2 = 'world';
String str3 = str1 + ' ' + str2;
print(str3); //输出:Hello world
也可以使用字符串内插(string interpolation)来将表达式的值嵌入到字符串中:
String name = 'John';
int age = 30;
String str = 'My name is $name. I am $age years old.';
print(str); //输出:My name is John. I am 30 years old.
在这个例子中,我们使用字符串内插将变量name和age的值嵌入到字符串中。
子字符串
要获取一个String的子字符串,可以使用substring()方法。substring方法有两个参数:起始索引和结束索引。
String str = 'Hello world';
String subStr1 = str.substring(0, 5); //从索引0开始,长度为5
String subStr2 = str.substring(6); //从索引6开始,到末尾
print(subStr1); //输出:Hello
print(subStr2); //输出:world
字符串查找
要查找一个String中的子串,可以使用indexOf()方法。如果能够找到子串,返回子串的起始位置(索引),否则返回-1。
String str = 'Hello world';
int index1 = str.indexOf('world'); //返回6
int index2 = str.indexOf('test'); //返回-1
print(index1);
print(index2);
还可以使用contains()方法来检查字符串是否包含另一个字符串。如果包含,返回true,否则返回false。
String str = 'Hello world';
bool contains1 = str.contains('world'); //返回true
bool contains2 = str.contains('test'); //返回false
print(contains1);
print(contains2);
字符串分割
要将一个字符串分割成多个字符串,可以使用split()方法。split方法有一个参数,用于指定分割字符串的分隔符。
String str = 'Hello,world,John,Doe';
List<String> list = str.split(',');
print(list); //输出["Hello", "world", "John", "Doe"]
字符串大小写转换
要将字符串转换为大写或小写,可以使用toUpperCase()和toLowerCase()方法。
String str = 'Hello world';
String upperStr = str.toUpperCase(); //转换为大写
String lowerStr = str.toLowerCase(); //转换为小写
print(upperStr); //输出:HELLO WORLD
print(lowerStr); //输出:hello world
结论
在Dart中,String是一种非常基本,也是非常重要的数据类型。本文中我们介绍了一些常见的String操作和用法,包括创建String、获取String长度、连接String、获取String子串、查找String中的子串、分割String以及将String转换为大写或小写,希望可以帮助初学者更好地理解Dart中String的使用。