【问题标题】:How to Capitalized each first letter for a Sentence in Flutter...?如何在 Flutter 中将每个句子的首字母大写......?
【发布时间】:2022-11-16 12:47:16
【问题描述】:

我想将 Flutter 句子中的每个首字母大写。??

这是一个大写的句子我期待从这是一个大写的句子

【问题讨论】:

    标签: flutter dart word letter


    【解决方案1】:
    extension StringExtension on String {
        String capitalize() {
          return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
        }
    }
    

    所以你可以像这样调用你的分机:

    import "string_extension.dart";
    
    var someCapitalizedString = "someString".capitalize();
    

    【讨论】:

      【解决方案2】:

      这是我制作的一个经过充分测试的方法:

      extension StringExtension on String {
      

      /// Capitalize the first letter of each word in a string /// /// dart /// String example = "hello world".capitalizeAllWordsFirstLetter(); // Hello World /// String capitalizeAllWordsFirstLetter() { String lowerCasedString = toLowerCase(); String stringWithoutExtraSpaces = lowerCasedString.trim();

      if (stringWithoutExtraSpaces.isEmpty) {
        return "";
      }
      if (stringWithoutExtraSpaces.length == 1) {
        return stringWithoutExtraSpaces.toUpperCase();
      }
      
      List<String> stringWordsList = stringWithoutExtraSpaces.split(" ");
      List<String> capitalizedWordsFirstLetter = stringWordsList
          .map(
            (word) {
              if (word.trim().isEmpty) return "";
              return word.trim();
            },
          )
          .where(
            (word) => word != "",
          )
          .map(
            (word) {
              if (word.startsWith(RegExp(r'[
      	
      ]'))) {
                return word;
              }
              return word[0].toUpperCase() + word.substring(1).toLowerCase();
            },
          )
          .toList();
      String finalResult = capitalizedWordsFirstLetter.join(" ");
      return finalResult;
      }}
      
       print("this is an example sentence"); // This Is An Example Sentence
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-25
        • 2017-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-23
        • 2012-05-20
        • 1970-01-01
        相关资源
        最近更新 更多