Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all whitespace from string

Tags:

How do I remove all whitespace from a string? I can think of some obvious methods such as looping over the string and removing each whitespace character, or using regular expressions, but these solutions are not that expressive or efficient. What is a simple and efficient way to remove all whitespace from a string?

like image 354
Magix Avatar asked Jul 16 '19 18:07

Magix


People also ask

How do I remove all white spaces from a string?

The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

How do you remove all the spaces from a string in JS?

JavaScript String trim() The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.

How do I remove all spaces from a string in TypeScript?

Use the replace() method to remove all whitespace from a string in TypeScript, e.g. str. replace(/\s/g, '') . The replace method takes a regular expression and a replacement string as parameters. The method will return a new string with all whitespace removed.


1 Answers

If you want to modify the String, use retain. This is likely the fastest way when available.

fn remove_whitespace(s: &mut String) {     s.retain(|c| !c.is_whitespace()); } 

If you cannot modify it because you still need it or only have a &str, then you can use filter and create a new String. This will, of course, have to allocate to make the String.

fn remove_whitespace(s: &str) -> String {     s.chars().filter(|c| !c.is_whitespace()).collect() } 
like image 143
JayDepp Avatar answered Sep 20 '22 17:09

JayDepp