如何在Dart中将字符串的第一个字母大写?

241

如何将字符串的第一个字符大写,同时不改变其他字母的大小写呢?

例如,"this is a string" 应该转换为 "This is a string"。

45个回答

339

自 Dart 2.6 版本以来,Dart 支持扩展:

extension StringExtension on String {
    String capitalize() {
      return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";
    }
}

那么你只需要像这样调用你的扩展:

import "string_extension.dart";

var someCapitalizedString = "someString".capitalize();

21
扩展应该返回 return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";。如果不这样做,它会正确地将 'this' 大写,但不会将 'THIS' 大写。 - Luciano Rodríguez
4
在执行操作前,通常不会先检查值是否有效吗? - Hannah Stark
2
我们要么在capitalize()函数内部检查isEmpty,要么将其留给调用者。我的偏好是让调用者处理,这样代码就不需要被.isEmpty()检查所淹没。你可以在第一行添加if (isEmpty) return this - Venkat D.
5
如果字符串不为null,你应该添加一些检查 - 例如: if (this == null || this == "") return ""; - Maciej
3
我本以为我喜欢Dart……但这个非常特别。为什么核心语言里没有类似的东西呢?我想知道还有什么其他的东西缺失了! - Gerry
显示剩余3条评论

281

复制这段内容到某个地方:

extension StringCasingExtension on String {
  String toCapitalized() => length > 0 ?'${this[0].toUpperCase()}${substring(1).toLowerCase()}':'';
  String toTitleCase() => replaceAll(RegExp(' +'), ' ').split(' ').map((str) => str.toCapitalized()).join(' ');
}

用法:

// import StringCasingExtension

final helloWorld = 'hello world'.toCapitalized(); // 'Hello world'
final helloWorld = 'hello world'.toUpperCase(); // 'HELLO WORLD'
final helloWorldCap = 'hello world'.toTitleCase(); // 'Hello World'

8
当字符串为空或长度不足时会发出投诉。 - Rishi Dua
21
作为开发人员,默认情况下,我们有责任检查这些条件。 - Jawand Singh
22
str.capitalize没有定义。所以你可以使用str.inCaps。 - Ashan
Uncaught Error: RangeError (index): Index out of range: no indices are valid: 0 - BIS Tech
1
final helloWorld = 'hello world'.capitalizeFirstofEach; - BIS Tech

177

其他答案中的子字符串解析并没有考虑本地化差异。 intl/intl.dart包中的toBeginningOfSentenceCase()函数处理基本的句子大小写和土耳其语和阿塞拜疆语中的点缀符号“i”。

import 'package:intl/intl.dart' show toBeginningOfSentenceCase;

print(toBeginningOfSentenceCase('this is a string'));

9
如果您已经使用intl包,那么没有必要用扩展方法重新发明轮子,这个加上扩展方法的答案应该就是答案。 - Gustavo Rodrigues
正是我所需要的。谢谢! - jwehrle
1
@GustavoRodrigues - 即使您目前没有使用Intl,这仍然是一个更好的答案,因为该软件包由Flutter / Dart团队维护,而扩展方法必须由开发人员维护。 - tim-montague
这是一个扩展程序,为什么需要维护呢? - dianesis
目前这个程序并没有进行任何特定于区域设置的逻辑处理(只是将第一个字母大写,特别处理土耳其语中的i)。但它可能在未来得到扩展。 - rjh
显示剩余3条评论

80

8
如果字符串最初是全大写的话,可以使用s[0].toUpperCase() + s.substring(1).toLowerCase();来将其转化为首字母大写、其余字母小写的格式。 - TomTom101

22

有一个utils包涵盖了该函数。它还有一些更好的操作字符串的方法。

安装方法如下:

dependencies:
  basic_utils: ^1.2.0

使用方法:

String capitalized = StringUtils.capitalize("helloworld");

Github:

https://github.com/Ephenodrom/Dart-Basic-Utils


不错的包。谢谢分享。 - Dani

21

虽然有点晚了,但我使用的是,


String title = "some string with no first letter caps";
    
title = title.replaceFirst(title[0], title[0].toUpperCase()); // Some string with no...


16

您可以在Flutter中使用此软件包 ReCase 它为您提供各种大小写转换功能,例如:

  • snake_case
  • dot.case
  • path/case
  • param-case
  • PascalCase
  • Header-Case
  • Title Case
  • camelCase
  • Sentence case
  • CONSTANT_CASE

    ReCase sample = new ReCase('hello world');
    
    print(sample.sentenceCase); // Prints 'Hello world'
    

很棒的库!! - Dario Brux
1
看起来不错。但是要谨慎使用,因为只有一个测试用例,无论你多么喜欢这个测试用例。String mockText = 'This is-Some_sampleText. YouDig?'; - WillHaslett

8

如Ephenodrom之前所述,您可以在pubspeck.yaml中添加basic_utils包,并在dart文件中像这样使用它:

StringUtils.capitalize("yourString");

这对于单个函数来说是可以接受的,但在更大的操作链中就变得笨拙了。
正如Dart语言文档中所解释的那样:
doMyOtherStuff(doMyStuff(something.doStuff()).doOtherStuff())

那段代码比以下的代码难以阅读得多:

something.doStuff().doMyStuff().doOtherStuff().doMyOtherStuff()

代码也更难发现,因为IDE可以在 something.doStuff() 之后建议 doMyStuff(),但不太可能建议在表达式周围放置 doMyOtherStuff(…)。出于这些原因,我认为你应该像这样为String类型添加一个扩展方法(你可以在dart 2.6中这样做!):
/// Capitalize the given string [s]
/// Example : hello => Hello, WORLD => World
extension Capitalized on String {
  String capitalized() => this.substring(0, 1).toUpperCase() + this.substring(1).toLowerCase();
}

并使用点表示法调用它:
'yourString'.capitalized()

如果你的值可以为空,那么在调用中用问号'?. '替换点号:

myObject.property?.toString()?.capitalized()

8
void allWordsCapitilize (String str) {
    return str.toLowerCase().split(' ').map((word) {
      String leftText = (word.length > 1) ? word.substring(1, word.length) : '';
      return word[0].toUpperCase() + leftText;
    }).join(' ');
}
allWordsCapitilize('THIS IS A TEST'); //This Is A Test

虽然这可能回答了问题,但您应该添加更多的注释来解释原因,以帮助提问者了解。 - Nguyễn Văn Phong
Uncaught Error: RangeError (index): Index out of range: no indices are valid: 0 - BIS Tech
String data = allWordsCapitilize('THIS IS A TEST') ; - BIS Tech

7
如果您正在使用 Flutter 的状态管理程序 get: ^4.6.5,那么它内置了大写字母的扩展功能。
        // This will capitalize first letter of every word
        print('hello world'.capitalize); // Hello World

        // This will capitalize first letter of sentence
        print('hello world'.capitalizeFirst); // Hello world

        // This will remove all white spaces from sentence
        print('hello world'.removeAllWhitespace); // helloworld

        // This will convert string to lowerCamelCase
        print('This is new world'.camelCase); // thisIsNewWorld

        // This will remove all white spaces between the two words and replace it with '-'
        print('This is new    world'.paramCase); // this-is-new-world

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接