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

Dart语言中移除字符串换行符\n的实现方案问询

Dart实现移除字符串中的换行符

给定字符串:

String item = 'Hello\nWorld'

需要实现removeBacklash函数,调用后移除字符串中的\n,得到HelloWorld,以下是具体实现:

基础实现(仅移除\n)

最直接的方式是使用String类的replaceAll方法,将所有\n替换为空字符串:

String removeBacklash(String input) {
  return input.replaceAll('\n', '');
}

// 调用示例
void main() {
  String item = 'Hello\nWorld';
  String newItem = removeBacklash(item);
  print(newItem); // 输出: HelloWorld
}

进阶实现(移除所有换行相关字符)

如果需要兼容不同操作系统的换行格式(比如Windows的\r\n、Mac旧版本的\r),可以使用正则表达式匹配所有换行类字符:

String removeBacklash(String input) {
  return input.replaceAll(RegExp(r'[\n\r]'), '');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:25:42