如何在Dart中删除字符串的所有空格?

bra*_*ule 3 dart flutter

使用trim()消除达特白色空间,这是行不通的。我做错了什么或有其他选择吗?

       String product = "COCA COLA";

       print('Product id is: ${product.trim()}');
Run Code Online (Sandbox Code Playgroud)

控制台打印: Product id is: COCA COLA

小智 43

这将解决您的问题

String name = "COCA COLA";
print(name.replaceAll(' ', ''));
Run Code Online (Sandbox Code Playgroud)


Par*_*iya 13

  1. 使用正则表达式 ( RegExp)

    如果原始字符串包含多个空格并且您想删除所有空格。应用以下解决方案

    String replaceWhitespacesUsingRegex(String s, String replace) {
     if (s == null) {
       return null;
     }
    
     // This pattern means "at least one space, or more"
     // \\s : space
     // +   : one or more
     final pattern = RegExp('\\s+');
     return s.replaceAll(pattern, replace);
    }
    
    Run Code Online (Sandbox Code Playgroud)

    像这样打电话

    print(replaceWhitespacesUsingRegex('One  Two   Three   Four', '')); // Output: 'OneTwoThreeFour'
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用 trim()

    trim()方法用于删除前导和尾随空格。它不会改变原始字符串。如果字符串末尾的开头没有空格,则返回原始值。

    print('   COCA COLA'.trim()); // Output: 'COCA COLA'
    print('COCA COLA     '.trim()); // Output: 'COCA COLA'
    print('   COCA COLA     '.trim()); // Output: 'COCA COLA'
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用 trimLeft()trimRight()

    如果您只想在开始时修剪而不是在结束时修剪,或者可能以相反的方式修剪怎么办。您可以trimLeft用于仅删除前导空格和trimRight仅删除尾随空格。

    print('   COCA COLA    '.trimLeft()); // Output: 'COCA COLA     '
    print('   COCA COLA    '.trimRight()); // Output:'   COCA COLA'
    
    Run Code Online (Sandbox Code Playgroud)

    如果 String 可以null,则可以考虑使用 null-aware 运算符。

    String s = null;
    print(s?.trim());
    
    Run Code Online (Sandbox Code Playgroud)

    上面的代码将返回null而不是抛出NoSuchMethodError

这个答案来自和作者:https : //www.woolha.com/tutorials/dart-trim-whitespaces-of-a-string-examples


Ste*_*wie 9

我知道这个问题有很好的答案,但我想展示一种奇特的方法来删除字符串中的所有空格。我实际上认为 Dart 应该有一个内置方法来处理这个问题,所以我为 String 类创建了以下扩展:

extension ExtendedString on String {
  /// The string without any whitespace.
  String removeAllWhitespace() {
    // Remove all white space.
    return this.replaceAll(RegExp(r"\s+"), "");
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以以非常简单和整洁的方式使用它:

String product = "COCA COLA";
print('Product id is: ${product.removeAllWhitespace()}');
Run Code Online (Sandbox Code Playgroud)


小智 7

尝试这个

String product = "COCA COLA";
print('Product id is: ${product.replaceAll(new RegExp(r"\s+\b|\b\s"), "")}');
Run Code Online (Sandbox Code Playgroud)


Shr*_*mal 6

Trim方法只删除开头和结尾。使用Regexp实例:这是一个示例: Dart:使用regexp从字符串中删除空格


小智 6

var s = "Coca Cola"; s.replaceAll(' ','');


小智 5

你可以试试这个:

String product = "COCA COLA";

print(product.split(" ").join(""));   // COCACOLA
Run Code Online (Sandbox Code Playgroud)