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

如何在Dart语言的指定位置将一个字符串插入另一个字符串?

在Dart中实现字符串插入功能

在Dart里虽然没有内置的String.Insert方法,但可以通过字符串拆分拼接或者扩展方法来实现需求,下面是两种常用方案:

  • 基础拼接法
    直接通过substring拆分原字符串,再和插入内容拼接,适合单次使用场景:
String original = "test";
String insertChar = "-";
int insertIndex = 2;

String output = original.substring(0, insertIndex) + insertChar + original.substring(insertIndex);
print(output); // 输出: te-st
  • 封装扩展方法(推荐复用场景)
    如果需要多次使用插入功能,可以给String类写一个扩展方法,用法和其他语言的Insert类似,还能添加参数校验:
extension StringInsertExtension on String {
  String insert(int index, String insertStr) {
    if (index < 0 || index > length) {
      throw ArgumentError("插入索引超出字符串范围");
    }
    return substring(0, index) + insertStr + substring(index);
  }
}

// 使用示例
String testStr = "test";
String result = testStr.insert(2, "-");
print(result); // 输出: te-st

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:02:09