String常用属性与方法详解
String常用属性与方法详解
String常用属性与方法详解
String 属性文档
length
📏** length → **int
介绍: 返回字符串的字符数量。
类似JS: String.prototype.length
示例:
1
2
String text = 'Hello Dart';
print(text.length); // 输出: 10
JS示例:
1
2
let text = 'Hello Dart';
console.log(text.length); // 输出: 10
isEmpty
🔍** isEmpty → **bool
介绍: 检查字符串是否为空(length 为 0)。
类似JS: str.length === 0
示例:
1
2
3
4
5
String emptyStr = '';
print(emptyStr.isEmpty); // 输出: true
String name = 'John';
print(name.isEmpty); // 输出: false
JS示例:
1
2
3
4
5
let emptyStr = '';
console.log(emptyStr.length === 0); // 输出: true
let name = 'John';
console.log(name.length === 0); // 输出: false
isNotEmpty
🔍** isNotEmpty → **bool
介绍: 检查字符串是否不为空(length > 0)。
类似JS: str.length > 0
示例:
1
2
3
4
5
String text = 'Hello';
print(text.isNotEmpty); // 输出: true
String emptyStr = '';
print(emptyStr.isNotEmpty); // 输出: false
JS示例:
1
2
3
4
5
let text = 'Hello';
console.log(text.length > 0); // 输出: true
let emptyStr = '';
console.log(emptyStr.length > 0); // 输出: false
String 方法文档
contains
🔍** contains(Pattern pattern, [int startIndex = 0]) → **bool
介绍: 检查字符串是否包含指定的模式。
类似JS: String.prototype.includes()
示例:
1
2
3
4
String text = 'Hello Dart Programming';
print(text.contains('Dart')); // 输出: true
print(text.contains('Flutter')); // 输出: false
print(text.contains(RegExp(r'[A-Z]'))); // 输出: true(包含大写字母)
JS示例:
1
2
3
4
let text = 'Hello Dart Programming';
console.log(text.includes('Dart')); // 输出: true
console.log(text.includes('Flutter')); // 输出: false
console.log(/[A-Z]/.test(text)); // 输出: true(包含大写字母)
indexOf
📍** indexOf(Pattern pattern, [int start = 0]) → **int
介绍: 返回指定模式第一次出现的索引,未找到返回 -1。
类似JS: String.prototype.indexOf()
示例:
1
2
3
4
String text = 'Hello Dart Dart';
print(text.indexOf('Dart')); // 输出: 6
print(text.indexOf('Dart', 7)); // 输出: 11
print(text.indexOf('Flutter')); // 输出: -1
JS示例:
1
2
3
4
let text = 'Hello Dart Dart';
console.log(text.indexOf('Dart')); // 输出: 6
console.log(text.indexOf('Dart', 7)); // 输出: 11
console.log(text.indexOf('Flutter')); // 输出: -1
lastIndexOf
📍** lastIndexOf(Pattern pattern, [int? start]) → **int
介绍: 返回指定模式最后一次出现的索引。
类似JS: String.prototype.lastIndexOf()
示例:
1
2
3
String text = 'Hello Dart Dart';
print(text.lastIndexOf('Dart')); // 输出: 11
print(text.lastIndexOf('l')); // 输出: 3
JS示例:
1
2
3
let text = 'Hello Dart Dart';
console.log(text.lastIndexOf('Dart')); // 输出: 11
console.log(text.lastIndexOf('l')); // 输出: 3
substring
✂️** substring(int start, [int? end]) → **String
介绍: 返回从 start 到 end(不包含)的子字符串。
类似JS: String.prototype.substring()
示例:
1
2
3
4
String text = 'Hello Dart';
print(text.substring(6)); // 输出: Dart
print(text.substring(0, 5)); // 输出: Hello
print(text.substring(2, 7)); // 输出: llo D
JS示例:
1
2
3
4
let text = 'Hello Dart';
console.log(text.substring(6)); // 输出: Dart
console.log(text.substring(0, 5)); // 输出: Hello
console.log(text.substring(2, 7)); // 输出: llo D
split
✂️** split(Pattern pattern) → **List<String>
介绍: 根据模式分割字符串,返回字符串列表。
类似JS: String.prototype.split()
示例:
1
2
3
4
5
6
7
8
9
10
11
12
String text = 'apple,banana,orange';
List<String> fruits = text.split(',');
print(fruits); // 输出: [apple, banana, orange]
String sentence = 'Hello World Dart';
List<String> words = sentence.split(' ');
print(words); // 输出: [Hello, World, Dart]
// 使用正则表达式分割
String data = 'apple1banana2orange3';
List<String> items = data.split(RegExp(r'\d'));
print(items); // 输出: [apple, banana, orange]
JS示例:
1
2
3
4
5
6
7
8
9
10
11
12
let text = 'apple,banana,orange';
let fruits = text.split(',');
console.log(fruits); // 输出: ['apple', 'banana', 'orange']
let sentence = 'Hello World Dart';
let words = sentence.split(' ');
console.log(words); // 输出: ['Hello', 'World', 'Dart']
// 使用正则表达式分割
let data = 'apple1banana2orange3';
let items = data.split(/\d/);
console.log(items); // 输出: ['apple', 'banana', 'orange']
replaceAll
🔄** replaceAll(Pattern from, String replace) → **String
介绍: 替换所有匹配的字符串。
类似JS: String.prototype.replaceAll()
示例:
1
2
3
4
5
6
7
8
String text = 'I like cats, cats are cute';
String replaced = text.replaceAll('cats', 'dogs');
print(replaced); // 输出: I like dogs, dogs are cute
// 使用正则表达式替换
String html = '<div>Hello</div>';
String clean = html.replaceAll(RegExp(r'<[^>]*>'), '');
print(clean); // 输出: Hello
JS示例:
1
2
3
4
5
6
7
8
let text = 'I like cats, cats are cute';
let replaced = text.replaceAll('cats', 'dogs');
console.log(replaced); // 输出: I like dogs, dogs are cute
// 使用正则表达式替换
let html = '<div>Hello</div>';
let clean = html.replaceAll(/<[^>]*>/g, '');
console.log(clean); // 输出: Hello
replaceFirst
🔄** replaceFirst(Pattern from, String to, [int startIndex = 0]) → **String
介绍: 替换第一个匹配的字符串。
类似JS: String.prototype.replace()(只替换第一个)
示例:
1
2
3
String text = 'apple banana apple';
String replaced = text.replaceFirst('apple', 'orange');
print(replaced); // 输出: orange banana apple
JS示例:
1
2
3
let text = 'apple banana apple';
let replaced = text.replace('apple', 'orange');
console.log(replaced); // 输出: orange banana apple
replaceRange
🔄** replaceRange(int start, int? end, String replacement) → **String
介绍: 替换指定范围内的字符。
类似JS: 无直接对应
示例:
1
2
3
4
5
6
7
String text = 'Hello World';
String replaced = text.replaceRange(6, 11, 'Dart');
print(replaced); // 输出: Hello Dart
// 只指定start,替换到末尾
String result = text.replaceRange(6, null, 'Flutter');
print(result); // 输出: Hello Flutter
JS示例:
1
2
3
4
// JavaScript 无直接对应方法,需要组合使用
let text = 'Hello World';
let replaced = text.substring(0, 6) + 'Dart';
console.log(replaced); // 输出: Hello Dart
startsWith
🎯** startsWith(Pattern pattern, [int index = 0]) → **bool
介绍: 检查字符串是否以指定模式开头。
类似JS: String.prototype.startsWith()
示例:
1
2
3
4
String text = 'Hello Dart';
print(text.startsWith('Hello')); // 输出: true
print(text.startsWith('Dart', 6)); // 输出: true
print(text.startsWith('Hi')); // 输出: false
JS示例:
1
2
3
4
let text = 'Hello Dart';
console.log(text.startsWith('Hello')); // 输出: true
console.log(text.startsWith('Dart', 6)); // 输出: true
console.log(text.startsWith('Hi')); // 输出: false
endsWith
🎯** endsWith(String other) → **bool
介绍: 检查字符串是否以指定字符串结尾。
类似JS: String.prototype.endsWith()
示例:
1
2
3
4
5
6
String text = 'hello.dart';
print(text.endsWith('.dart')); // 输出: true
print(text.endsWith('.js')); // 输出: false
String fileName = 'image.png';
print(fileName.endsWith('.png')); // 输出: true
JS示例:
1
2
3
4
5
6
let text = 'hello.dart';
console.log(text.endsWith('.dart')); // 输出: true
console.log(text.endsWith('.js')); // 输出: false
let fileName = 'image.png';
console.log(fileName.endsWith('.png')); // 输出: true
toLowerCase
📝** toLowerCase() → **String
介绍: 将字符串转换为小写。
类似JS: String.prototype.toLowerCase()
示例:
1
2
3
4
5
String text = 'Hello Dart';
print(text.toLowerCase()); // 输出: hello dart
String mixed = 'Flutter&Dart';
print(mixed.toLowerCase()); // 输出: flutter&dart
JS示例:
1
2
3
4
5
let text = 'Hello Dart';
console.log(text.toLowerCase()); // 输出: hello dart
let mixed = 'Flutter&Dart';
console.log(mixed.toLowerCase()); // 输出: flutter&dart
toUpperCase
📝** toUpperCase() → **String
介绍: 将字符串转换为大写。
类似JS: String.prototype.toUpperCase()
示例:
1
2
3
4
5
String text = 'Hello Dart';
print(text.toUpperCase()); // 输出: HELLO DART
String mixed = 'Flutter&Dart';
print(mixed.toUpperCase()); // 输出: FLUTTER&DART
JS示例:
1
2
3
4
5
let text = 'Hello Dart';
console.log(text.toUpperCase()); // 输出: HELLO DART
let mixed = 'Flutter&Dart';
console.log(mixed.toUpperCase()); // 输出: FLUTTER&DART
trim
🧹** trim() → **String
介绍: 去除字符串首尾的空白字符。
类似JS: String.prototype.trim()
示例:
1
2
3
4
5
String text = ' Hello Dart ';
print(text.trim()); // 输出: Hello Dart
String withNewline = '\nHello Dart\n';
print(withNewline.trim()); // 输出: Hello Dart
JS示例:
1
2
3
4
5
let text = ' Hello Dart ';
console.log(text.trim()); // 输出: Hello Dart
let withNewline = '\nHello Dart\n';
console.log(withNewline.trim()); // 输出: Hello Dart
trimLeft
🧹** trimLeft() → **String
介绍: 去除字符串开头的空白字符。
类似JS: String.prototype.trimStart()
示例:
1
2
String text = ' Hello Dart ';
print(text.trimLeft()); // 输出: Hello Dart
JS示例:
1
2
let text = ' Hello Dart ';
console.log(text.trimStart()); // 输出: Hello Dart
trimRight
🧹** trimRight() → **String
介绍: 去除字符串末尾的空白字符。
类似JS: String.prototype.trimEnd()
示例:
1
2
String text = ' Hello Dart ';
print(text.trimRight()); // 输出: Hello Dart
JS示例:
1
2
let text = ' Hello Dart ';
console.log(text.trimEnd()); // 输出: Hello Dart
padLeft
🔍** padLeft(int width, [String padding = ‘ ‘]) → **String
介绍: 在字符串左侧填充字符直到达到指定宽度。
类似JS: String.prototype.padStart()
示例:
1
2
3
4
5
6
String number = '5';
print(number.padLeft(3, '0')); // 输出: 005
String text = 'Hi';
print(text.padLeft(5)); // 输出: Hi
print(text.padLeft(5, '*')); // 输出: ***Hi
JS示例:
1
2
3
4
5
6
let number = '5';
console.log(number.padStart(3, '0')); // 输出: 005
let text = 'Hi';
console.log(text.padStart(5)); // 输出: Hi
console.log(text.padStart(5, '*')); // 输出: ***Hi
padRight
🔍** padRight(int width, [String padding = ‘ ‘]) → **String
介绍: 在字符串右侧填充字符直到达到指定宽度。
类似JS: String.prototype.padEnd()
示例:
1
2
3
4
5
6
String number = '5';
print(number.padRight(3, '0')); // 输出: 500
String text = 'Hi';
print(text.padRight(5)); // 输出: Hi
print(text.padRight(5, '-')); // 输出: Hi---
JS示例:
1
2
3
4
5
6
let number = '5';
console.log(number.padEnd(3, '0')); // 输出: 500
let text = 'Hi';
console.log(text.padEnd(5)); // 输出: Hi
console.log(text.padEnd(5, '-')); // 输出: Hi---
compareTo
🔍** compareTo(String other) → **int
介绍: 比较两个字符串,返回比较结果。
类似JS: String.prototype.localeCompare()
示例:
1
2
3
4
5
6
7
8
9
10
String a = 'apple';
String b = 'banana';
print(a.compareTo(b)); // 输出: -1(a < b)
print(b.compareTo(a)); // 输出: 1(b > a)
print(a.compareTo('apple')); // 输出: 0(相等)
// 实际应用:字符串排序
List<String> fruits = ['banana', 'apple', 'cherry'];
fruits.sort((a, b) => a.compareTo(b));
print(fruits); // 输出: [apple, banana, cherry]
JS示例:
1
2
3
4
5
6
7
8
9
10
let a = 'apple';
let b = 'banana';
console.log(a.localeCompare(b)); // 输出: -1(a < b)
console.log(b.localeCompare(a)); // 输出: 1(b > a)
console.log(a.localeCompare('apple')); // 输出: 0(相等)
// 实际应用:字符串排序
let fruits = ['banana', 'apple', 'cherry'];
fruits.sort((a, b) => a.localeCompare(b));
console.log(fruits); // 输出: ['apple', 'banana', 'cherry']
codeUnitAt
🔍** codeUnitAt(int index) → **int
介绍: 返回指定索引处字符的 UTF-16 码元。
类似JS: String.prototype.charCodeAt()
示例:
1
2
3
String text = 'Hello';
print(text.codeUnitAt(0)); // 输出: 72(H的ASCII码)
print(text.codeUnitAt(1)); // 输出: 101(e的ASCII码)
JS示例:
1
2
3
let text = 'Hello';
console.log(text.charCodeAt(0)); // 输出: 72(H的ASCII码)
console.log(text.charCodeAt(1)); // 输出: 101(e的ASCII码)
codeUnits
🔍** codeUnits → **List<int>
介绍: 返回字符串的 UTF-16 码元列表。
类似JS: 无直接对应
示例:
1
2
3
4
5
String text = 'Hi';
print(text.codeUnits); // 输出: [72, 105]
String emoji = '😀';
print(emoji.codeUnits); // 输出: [55357, 56832]
JS示例:
1
2
3
4
5
6
7
// JavaScript 需要手动实现
let text = 'Hi';
let codeUnits = [];
for (let i = 0; i < text.length; i++) {
codeUnits.push(text.charCodeAt(i));
}
console.log(codeUnits); // 输出: [72, 105]
runes
🔍** runes → **Runes
介绍: 返回字符串的 Unicode 码点迭代器。
类似JS: 无直接对应
示例:
1
2
3
4
5
String text = 'Hello';
print(text.runes.toList()); // 输出: [72, 101, 108, 108, 111]
String emoji = '😀🎉';
print(emoji.runes.toList()); // 输出: [128512, 127881]
JS示例:
1
2
3
4
5
6
7
// JavaScript 可以使用 codePointAt
let text = 'Hello';
let codePoints = [];
for (let i = 0; i < text.length; i++) {
codePoints.push(text.codePointAt(i));
}
console.log(codePoints); // 输出: [72, 101, 108, 108, 111]
toString
🔗** toString() → **String
介绍: 返回字符串本身(String 类重写的方法)。
类似JS: String.prototype.toString()
示例:
1
2
3
4
5
6
String text = 'Hello';
print(text.toString()); // 输出: Hello
// 实际开发中主要用于对象转字符串
int number = 42;
print(number.toString()); // 输出: 42
JS示例:
1
2
3
4
5
6
let text = 'Hello';
console.log(text.toString()); // 输出: Hello
// 实际开发中主要用于对象转字符串
let number = 42;
console.log(number.toString()); // 输出: 42
matchAsPrefix
🔍** matchAsPrefix(String string, [int start = 0]) → **Match?
介绍: 检查字符串是否从指定位置开始匹配模式。
类似JS: RegExp.prototype.exec()
示例:
1
2
3
4
5
6
7
8
String text = 'Hello World';
RegExp pattern = RegExp(r'Hello');
Match? match = pattern.matchAsPrefix(text);
print(match != null); // 输出: true
Match? noMatch = pattern.matchAsPrefix(text, 6);
print(noMatch != null); // 输出: false
JS示例:
1
2
3
4
5
6
7
8
let text = 'Hello World';
let pattern = /Hello/;
let match = pattern.exec(text);
console.log(match !== null); // 输出: true
let noMatch = pattern.exec(text.substring(6));
console.log(noMatch !== null); // 输出: false
allMatches
🔍** allMatches(String input, [int start = 0]) → **Iterable<Match>
介绍: 查找所有匹配的模式。
类似JS: String.prototype.matchAll()
示例:
1
2
3
4
5
6
7
8
9
10
11
12
String text = 'apple banana apple cherry';
RegExp pattern = RegExp(r'apple');
Iterable<Match> matches = pattern.allMatches(text);
print(matches.length); // 输出: 2
for (Match match in matches) {
print('找到匹配: ${match.group(0)} 在位置 ${match.start}');
}
// 输出:
// 找到匹配: apple 在位置 0
// 找到匹配: apple 在位置 13
JS示例:
1
2
3
4
5
6
7
8
9
10
11
12
let text = 'apple banana apple cherry';
let pattern = /apple/g;
let matches = [...text.matchAll(pattern)];
console.log(matches.length); // 输出: 2
for (let match of matches) {
console.log(`找到匹配: ${match[0]} 在位置 ${match.index}`);
}
// 输出:
// 找到匹配: apple 在位置 0
// 找到匹配: apple 在位置 13
补充说明
注意事项
- 字符串不可变: 所有方法都返回新字符串,不会修改原字符串
- Unicode 支持: Dart 字符串是 UTF-16 编码,支持完整的 Unicode 字符集
- 性能考虑: 大量字符串操作时考虑使用
StringBuffer - 正则表达式: Dart 使用
RegExp类处理正则表达式,语法与 JavaScript 类似
常用开发场景
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 1. 字符串验证
bool isValidEmail(String email) {
return email.contains('@') && email.endsWith('.com');
}
// 2. 字符串格式化
String formatPrice(double price) {
return '\$${price.toStringAsFixed(2)}';
}
// 3. 字符串分割处理
List<String> parseCSV(String csv) {
return csv.split(',').map((item) => item.trim()).toList();
}
// 4. 模板字符串(Dart 使用字符串插值)
String greet(String name, int age) {
return 'Hello, $name! You are $age years old.';
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// JavaScript 对应示例
// 1. 字符串验证
function isValidEmail(email) {
return email.includes('@') && email.endsWith('.com');
}
// 2. 字符串格式化
function formatPrice(price) {
return `\$${price.toFixed(2)}`;
}
// 3. 字符串分割处理
function parseCSV(csv) {
return csv.split(',').map(item => item.trim());
}
// 4. 模板字符串
function greet(name, age) {
return `Hello, ${name}! You are ${age} years old.`;
}
这份文档涵盖了 Dart String 的主要属性和方法,提供了完整的类型信息和实际开发示例,同时给出了对应的 JavaScript 示例,帮助开发者更好地理解和使用字符串操作。