【发布时间】:2021-07-15 13:00:27
【问题描述】:
我在 dart 中找到了将普通字符串转换为骆驼大小写和蛇大小写的方法,但我想将 SnakeCase 实现为普通句子。
例如:myNameIsJohnDoe 到 我的名字是 john doe
【问题讨论】:
-
到目前为止你做了什么?你能分享一下你之前尝试过的东西吗?
标签: android flutter dart dart-pub
我在 dart 中找到了将普通字符串转换为骆驼大小写和蛇大小写的方法,但我想将 SnakeCase 实现为普通句子。
例如:myNameIsJohnDoe 到 我的名字是 john doe
【问题讨论】:
标签: android flutter dart dart-pub
有几种方法可以做到:
import 'package:recase/recase.dart';
void main() {
print("my_name_is_john_doe".sentenceCase); //snake_case to normal sentence;
print("myNameIsJohnDoe".sentenceCase); //camelCase to normal Sentence;
print("my_name_is_john_doe".snakeCasetoSentenceCase()); //Other way of converting snake case to Normal Sentence
}
extension StringExtension on String {
String snakeCasetoSentenceCase() {
return "${this[0].toUpperCase()}${this.substring(1)}"
.replaceAll(RegExp(r'(_|-)+'), ' ');
}
}
输出:
My name is john doe
My name is john doe
My name is john doe
【讨论】:
Flutter Only 解决方案,因为get 不支持纯飞镖
你可以试试这个:
String text = 'myNameIsJohnDoe';
RegExp exp = RegExp(r'(?<=[a-z])[A-Z]');
String result = text.replaceAllMapped(exp, (Match m) => (' ' + m.group(0))).capitalizeFirst;
print('Result : $result');
输出:
Result : My name is John doe
#UPDATE:
安装get以使用capitalizeFirst
dependencies:
get: ^4.1.4
导入它,现在在你的 Dart 代码中,你可以使用:
import 'package:get/get.dart';
【讨论】:
The getter 'capitalizeFirst' isn't defined for the class 'String'.