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

Kas*_*per 35 dart

如何大写字符串的第一个字符,而不更改任何其他字母的大小写?

例如,"this is a string"应该给出"This is a string".

Han*_*ark 154

从 dart 2.6 版开始,dart 支持扩展:

extension StringExtension on String {
    String capitalize() {
      return "${this[0].toUpperCase()}${this.substring(1)}";
    }
}
Run Code Online (Sandbox Code Playgroud)

所以你可以像这样调用你的扩展:

import "string_extension.dart";

var someCapitalizedString = "someString".capitalize();
Run Code Online (Sandbox Code Playgroud)

  • 扩展应返回 `return "${this[0].toUpperCase()}${this.substring(1).toLowerCase()}";`。如果不是,它将正确地大写“this”,但不会正确地大写“THIS”。 (13认同)
  • 在使用某个值之前,您通常不会检查它是否有效吗? (3认同)
  • 我以为我喜欢 Dart……但这很特别。为什么他们不在核心语言中使用类似的东西?我想知道还缺少什么! (3认同)
  • 我们要么必须检查 Capitalize() 中的 isEmpty 要么将其留给调用者。我的偏好是针对调用者,因此代码不需要充斥着 .isEmpty() 检查。您可以添加“if (isEmpty) return this”作为第一行。 (2认同)
  • 如果字符串不为空,您应该添加一些检查 - 例如: `if (this == null || this == "") return ""; ` (2认同)

Gün*_*uer 43

main() {
  String s = 'this is a string';
  print('${s[0].toUpperCase()}${s.substring(1)}');
}
Run Code Online (Sandbox Code Playgroud)

  • `str.capitalize` _未定义_。所以你使用“str.inCaps” (19认同)
  • @RishiDua和开发人员一样,(默认情况下)我们有责任检查这些条件 (7认同)
  • 当字符串为空或不够长时会抱怨. (5认同)

Ale*_*uin 32

void main() {
  print(capitalize("this is a string"));
  // displays "This is a string"
}

String capitalize(String s) => s[0].toUpperCase() + s.substring(1);
Run Code Online (Sandbox Code Playgroud)

请参阅在DartPad上运行的此代码段:https://dartpad.dartlang.org/c8ffb8995abe259e9643

或者您可以使用strings包,请参阅capitalize.

  • `s[0].toUpperCase() + s.substring(1).toLowerCase();` 如果字符串开头全部大写。 (3认同)

Nit*_*Sai 22

超级晚了,但我用,


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

Run Code Online (Sandbox Code Playgroud)


Eph*_*rom 17

有一个涵盖此功能的 utils 包。它有一些更好的字符串操作方法。

安装它:

dependencies:
  basic_utils: ^1.2.0
Run Code Online (Sandbox Code Playgroud)

用法 :

dependencies:
  basic_utils: ^1.2.0
Run Code Online (Sandbox Code Playgroud)

GitHub:

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


Jen*_*enn 12

其他答案中的子字符串解析不考虑区域差异。程序包中的toBeginningOfSentenceCase()函数intl/intl.dart处理基本的句子大小写以及土耳其语和阿塞拜疆语中带点划线的“ i”。

import 'package:intl/intl.dart';
...
String sentence = toBeginningOfSentenceCase('this is a string'); // This is a string
Run Code Online (Sandbox Code Playgroud)

  • 除了扩展方法答案之外,这应该是答案。如果您已经使用 intl 包,则没有理由使用扩展重新发明轮子。 (11认同)
  • @GustavoRodrigues - 即使您当前没有使用 Intl,这也是一个更好的答案,因为这个包由 Flutter / Dart 团队维护,而扩展方法必须由开发人员维护。 (2认同)

Mah*_*ahi 9

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

  • 蛇案例
  • 点.case
  • 路径/案例
  • 参数案例
  • 帕斯卡案例
  • 标题案例
  • 标题案例
  • 骆驼香烟盒
  • 判例案
  • CONSTANT_CASE

    ReCase sample = new ReCase('hello world');
    
    print(sample.sentenceCase); // Prints 'Hello world'
    
    Run Code Online (Sandbox Code Playgroud)


小智 8

正如 Ephenodrom 之前提到的,\n您可以在 pubspeck.yaml 中添加 basic_utils 包,并在 dart 文件中使用它,如下所示:

\n
StringUtils.capitalize("yourString");\n
Run Code Online (Sandbox Code Playgroud)\n

这对于单个功能来说是可以接受的,但在更大的操作链中,这就变得很尴尬。

\n

正如Dart 语言文档中所解释的:

\n
doMyOtherStuff(doMyStuff(something.doStuff()).doOtherStuff())\n
Run Code Online (Sandbox Code Playgroud)\n

该代码的可读性比以下代码要差得多:

\n
something.doStuff().doMyStuff().doOtherStuff().doMyOtherStuff()\n
Run Code Online (Sandbox Code Playgroud)\n

该代码也更难被发现,因为 IDE 可以建议doMyStuff()after something.doStuff(),但不太可能建议将doMyOtherStuff(\xe2\x80\xa6)表达式放在周围。

\n

出于这些原因,我认为你应该为 String 类型添加一个扩展方法(从 dart 2.6 开始就可以这样做!),如下所示:

\n
/// Capitalize the given string [s]\n/// Example : hello => Hello, WORLD => World\nextension Capitalized on String {\n  String capitalized() => this.substring(0, 1).toUpperCase() + this.substring(1).toLowerCase();\n}\n
Run Code Online (Sandbox Code Playgroud)\n

并使用点表示法调用它:

\n
\'yourString\'.capitalized()\n
Run Code Online (Sandbox Code Playgroud)\n

或者,如果您的值可以为 null,则在调用中将点替换为 \'?.\':

\n
myObject.property?.toString()?.capitalized()\n
Run Code Online (Sandbox Code Playgroud)\n


小智 8

如果您使用 get: ^4.6.5 作为 flutter 的状态管理,那么有用于大写的内置扩展

        // 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
Run Code Online (Sandbox Code Playgroud)


And*_*rey 5

String capitalize(String s) => (s != null && s.length > 1)
    ? s[0].toUpperCase() + s.substring(1)
    : s != null ? s.toUpperCase() : null;
Run Code Online (Sandbox Code Playgroud)

它通过了测试:

test('null input', () {
  expect(capitalize(null), null);
});
test('empty input', () {
  expect(capitalize(''), '');
});
test('single char input', () {
  expect(capitalize('a'), 'A');
});
test('crazy input', () {
  expect(capitalize('?a!'), '?a!');
});
test('normal input', () {
  expect(capitalize('take it easy bro!'), 'Take it easy bro!');
});
Run Code Online (Sandbox Code Playgroud)


小智 5

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
Run Code Online (Sandbox Code Playgroud)


Gül*_*kin 5

String? toCapitalize(String? input) {
  if (input == null || input.isEmpty) return input;
  return '${input[0].toUpperCase()}${input.substring(1).toLowerCase()}';
}
Run Code Online (Sandbox Code Playgroud)

或扩展名:

extension StringExtension on String {
  String? toCapitalize() {
    if (this == null || this.isEmpty) return this;
    return '${this[0].toUpperCase()}${this.substring(1).toLowerCase()}';
  }
}
Run Code Online (Sandbox Code Playgroud)