yx_icon_fonts_flutter/lib/src/utils/string_helper.dart

67 lines
1.9 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/// 字符串工具类
///
/// 提供字符串转换和格式化功能
class StringHelper {
/// 私有构造函数,防止实例化
StringHelper._();
/// 下划线转驼峰命名
///
/// 例如icon_32_clean -> icon32Clean
static String toCamelCase(String input) {
// 预处理:将常见特殊字符转换
final processedInput = input
.replaceAll('-', '_')
.replaceAll('+', 'plus')
.replaceAll('(', '')
.replaceAll(')', '')
.replaceAll(' ', '');
final parts = processedInput.split('_');
if (parts.isEmpty) return input;
final firstPart = parts[0];
final remainingParts = parts.skip(1).map((part) {
if (part.isEmpty) return '';
return part[0].toUpperCase() + part.substring(1);
}).join();
return firstPart + remainingParts;
}
/// 转换为合法的 Dart 标识符
///
/// 确保首字符不是数字,只包含字母、数字和下划线
static String toLegalDartName(String input) {
var name = toCamelCase(input);
// 首字符为数字,前面加下划线
if (name.isNotEmpty && RegExp('^[0-9]').hasMatch(name[0])) {
name = '_$name';
}
// 只保留字母、数字和下划线
return name.replaceAll(RegExp('[^a-zA-Z0-9_]'), '');
}
/// 转换为 PascalCase首字母大写的驼峰命名
///
/// 例如icon_class -> IconClass
static String toPascalCase(String input) {
final camelCase = toCamelCase(input);
if (camelCase.isEmpty) return camelCase;
return camelCase[0].toUpperCase() + camelCase.substring(1);
}
/// 格式化时间长度
static String formatDuration(Duration duration) {
if (duration.inMinutes > 0) {
return '${duration.inMinutes}m ${duration.inSeconds % 60}s';
} else if (duration.inSeconds > 0) {
return '${duration.inSeconds}.${(duration.inMilliseconds % 1000) ~/ 100}s';
} else {
return '${duration.inMilliseconds}ms';
}
}
}