【问题标题】:How to convert snake case to normal sentence in Dart? [closed]如何在 Dart 中将蛇案例转换为正常句子? [关闭]
【发布时间】:2021-07-15 13:00:27
【问题描述】:

我在 dart 中找到了将普通字符串转换为骆驼大小写和蛇大小写的方法,但我想将 SnakeCase 实现为普通句子。

例如:myNameIsJohnDoe我的名字是 john doe

【问题讨论】:

  • 到目前为止你做了什么?你能分享一下你之前尝试过的东西吗?

标签: android flutter dart dart-pub


【解决方案1】:

有几种方法可以做到:

  1. 使用recase
  2. 使用扩展方法
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

【讨论】:

    【解决方案2】:

    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';
    

    【讨论】:

    • 我的 dart 编译器似乎找不到 capitalizeFirst The getter 'capitalizeFirst' isn't defined for the class 'String'.
    • 查看更新答案@AmanVerma
    猜你喜欢
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多