在 Flutter 中删除 String 对象中特定字符之后的所有字符的最佳方法是什么?
假设我有以下字符串:
一二
我需要从中删除“.two”。我该怎么做?
提前致谢。
Car*_*yes 21
您可以使用类中的subString方法String
String s = "one.two";
//Removes everything after first '.'
String result = s.substring(0, s.indexOf('.'));
print(result);
Run Code Online (Sandbox Code Playgroud)
如果有多个'.' 在String它将使用第一次出现。如果您需要使用最后一个(例如删除文件扩展名),请更改indexOf为lastIndexOf. 如果您不确定是否至少发生了一次,您还应该添加一些验证以避免触发异常。
String s = "one.two.three";
//Remove everything after last '.'
var pos = s.lastIndexOf('.');
String result = (pos != -1)? s.substring(0, pos): s;
print(result);
Run Code Online (Sandbox Code Playgroud)
Bla*_*nka 15
void main() {
String str = "one.two";
print(str.replaceAll(".two", ""));
// or
print(str.split(".").first);
// or
String newStr = str.replaceRange(str.indexOf("."), str.length, "");
print(newStr);
// Lets do a another example
String nums = "1,one.2,two.3,three.4,four";
List values = nums.split("."); // split() will split from . and gives new List with separated elements.
values.forEach(print);
//output
// 1,one
// 2,two
// 3,three
// 4,four
}
Run Code Online (Sandbox Code Playgroud)
在DartPad中编辑它。
其实,还有其他很酷的方法String。在这里检查一下。
答案在上面,但如果您只想要特定的角色位置或位置,这里是您可以如何做到的。
\n要从 Dart String 中获取子字符串,我们使用substring()方法:
String str = \'bezkoder.com\';\n\n// For example, here we want \xe2\x80\x98r\xe2\x80\x99 is the ending. In \xe2\x80\x98bezkoder.com\xe2\x80\x99,\n// the index of \xe2\x80\x98r\xe2\x80\x99 is 7. So we need to set endIndex by 8.\nstr.substring(0,8); // bezkoder\n\nstr.substring(2,8); // zkoder\nstr.substring(3); // koder.com\nRun Code Online (Sandbox Code Playgroud)\nsubstring()这是返回字符串的方法的签名:
String substring(int startIndex, [int endIndex]);\nRun Code Online (Sandbox Code Playgroud)\nstartIndex:开始的字符索引。开始索引为 0。\n endIndex(可选):结束字符索引 + 1。如果未设置,结果将为从 startIndex 到字符串末尾的子字符串。
[参考]\n[1]: https: //bezkoder.com/dart-string-methods-operators-examples/
\nString str = "one.two";
var value = str?.replaceFirst(RegExp(r"\.[^]*"), "");
Run Code Online (Sandbox Code Playgroud)
str.substring(0, str.indexOf('.'));如果您确定str包含,您可以使用.
否则你会得到错误Value not in range: -1。
| 归档时间: |
|
| 查看次数: |
20470 次 |
| 最近记录: |