在Dart中使用trim()
来消除空格,但它不起作用。我做错了什么,还是有其他方法?
String product = "COCA COLA";
print('Product id is: ${product.trim()}');
控制台输出:产品ID是:COCA COLA
在Dart中使用trim()
来消除空格,但它不起作用。我做错了什么,还是有其他方法?
String product = "COCA COLA";
print('Product id is: ${product.trim()}');
控制台输出:产品ID是:COCA COLA
这将解决你的问题。
String name = "COCA COLA";
print(name.replaceAll(' ', ''));
试试这个
String product = "COCA COLA";
print('Product id is: ${product.replaceAll(new RegExp(r"\s+\b|\b\s"), "")}');
更新:
String name = '4 ever 1 k g @@ @';
print(name.replaceAll(RegExp(r"\s+"), ""));
另一个简单的解决方案:
String name = '4 ever 1 k g @@ @';
print(name.replaceAll(' ', '');
String name = '4 ever 1 k g @@ @'; print(name.replaceAll(new RegExp(r"\s+\b|\b\s"), ""));
- BIS Tech我知道这个问题已经有了很好的答案,但我想展示一种花哨的方法来删除字符串中的所有空格。实际上,我认为Dart应该有一个内置的方法来处理这个问题,因此我创建了以下用于String类的扩展:
extension ExtendedString on String {
/// The string without any whitespace.
String removeAllWhitespace() {
// Remove all white space.
return this.replaceAll(RegExp(r"\s+"), "");
}
}
现在,你可以非常简洁和整洁地使用它:
String product = "COCA COLA";
print('Product id is: ${product.removeAllWhitespace()}');
var s = "可口可乐"; s.replaceAll(' ','');
s
保持不变。其次,即使这样做起作用了,它真的比顶部答案多添加了什么吗? - General GrievanceString product = "COCA COLA";
print(product.split(" ").join("")); // COCACOLA
有很多方法可以做到这一点。
最明显的方法:
String product = "COCA COLA";
print('Product id is: ${product.replaceAll(' ', '')}'); // COCACOLA
使用普通函数:
String removeAllWhitespaces(String string) {
return string.replaceAll(' ', '');
}
String product = "COCA COLA";
print('Product id is: ${removeAllWhitespaces(product)}'); // COCACOLA
使用扩展方法:
extension StringRemoveWhitespace on String {
String get removeAllWhitespaces => replaceAll(' ', ''); // COCACOLA
}
String product = "COCA COLA";
print('Product id is: ${product.removeAllWhitespaces}');
extension StringExtensions on String {
String removeWhitespace() {
return this.replaceAll(' ', '');
}
}
这可以像这样调用:product.removeWhiteSpace()
。我曾经在排序列表时使用它来创建一个帮助方法,同时忽略大小写和空格。
extension StringExtensions on String {
String toSortable() {
return this.toLowerCase().replaceAll(' ', '');
}
}
使用 Trim 函数
String name = "Stack Overflow";
print(name.trim());