You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何实现句子每个单词首字母大写?

Flutter实现句子中每个单词首字母大写

下面提供两种实用的实现方式,满足将句子中每个单词首字母转为大写的需求:

方法一:原生字符串处理(无需依赖)

手动拆分字符串并逐个处理单词,适合不想引入第三方包的场景:

String capitalizeEachWord(String input) {
  if (input.isEmpty) return input;
  // 处理多个连续空格的情况,拆分后过滤空字符串
  List<String> words = input.trim().split(RegExp(r'\s+'));
  return words.map((word) {
    if (word.length == 1) {
      return word.toUpperCase();
    }
    // 首字母大写,其余字母转为小写(如果需要保留原大小写,去掉.toLowerCase()即可)
    return word[0].toUpperCase() + word.substring(1).toLowerCase();
  }).join(' ');
}

// 调用示例
void main() {
  String input = "This is a capitalized sentence";
  String output = capitalizeEachWord(input);
  print(output); // 输出: This Is A Capitalized Sentence
}

方法二:借助Intl包(快速实现)

如果项目中已经使用了intl包,可以利用其内置方法简化代码:

  1. 先在pubspec.yaml中添加依赖:
dependencies:
  intl: ^0.18.1
  1. 实现代码:
import 'package:intl/intl.dart';

String capitalizeEachWord(String input) {
  if (input.isEmpty) return input;
  return input.split(RegExp(r'\s+'))
      .map((word) => toBeginningOfSentenceCase(word))
      .join(' ');
}

// 调用示例
void main() {
  String input = "This is a capitalized sentence";
  String output = capitalizeEachWord(input);
  print(output); // 输出: This Is A Capitalized Sentence
}

注意事项

  • 两种方法都处理了连续多个空格的情况,最终输出会合并为单个空格。
  • 如果需要保留单词中除首字母外的原大小写(比如输入"This IS A test"想得到"This IS A Test"),只需将方法一中的word.substring(1).toLowerCase()改为word.substring(1)即可。

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 19:20:46