Flutter中如何将字符串中的'\n'替换为'|'?
解决Flutter/Dart中字符串换行替换无效的问题
首先得揪出问题的根源:你定义的myString里压根没有换行符(\n)!因为你把所有文本都挤在了同一行的三重引号里,Dart的三重引号只会保留你在代码里实际敲出来的换行,而不是句子之间的空格。
解决方案一:正确定义带换行的字符串
如果你原本就想让字符串包含换行,那定义的时候要把每一行分开写,让代码里的换行被三重引号捕获:
String myString = ''' this is my first line this is the second line this is the third one '''; // 先去掉首尾多余的换行和空格,再替换换行符 String result = myString.trim().replaceAll(RegExp(r'\n'), '|'); print(result); // 输出:this is my first line|this is the second line|this is the third one
解决方案二:如果原字符串是空格分隔的句子
如果你的实际字符串里并没有换行,只是用空格分隔了三个句子,那你需要替换的是连续空格而非换行符,用正则匹配更稳妥:
String myString = ''' this is my first line this is the second line this is the third one '''; // 先去掉首尾空格,再把连续空格替换成| String result = myString.trim().replaceAll(RegExp(r'\s+'), '|'); print(result); // 输出:this is my first line|this is the second line|this is the third one
小提醒
别忘了Dart的字符串是不可变的!replaceAll()会返回一个新字符串,不会修改原myString,一定要把返回值存起来再打印哦~
内容的提问来源于stack exchange,提问作者JakesMD
相关产品推荐
相关产品推荐

