Efficient Way to Remove All Whitespace from String

Efficient way to remove ALL whitespace from String?

This is fastest way I know of, even though you said you didn't want to use regular expressions:

Regex.Replace(XML, @"\s+", "");

Crediting @hypehuman in the comments, if you plan to do this more than once, create and store a Regex instance. This will save the overhead of constructing it every time, which is more expensive than you might think.

private static readonly Regex sWhitespace = new Regex(@"\s+");
public static string ReplaceWhitespace(string input, string replacement)
{
return sWhitespace.Replace(input, replacement);
}

How to remove all whitespace characters from a String?

Try using Linq in order to filter out white spaces:

  using System.Linq;

...

string source = "abc \t def\r\n789";
string result = string.Concat(source.Where(c => !char.IsWhiteSpace(c)));

Console.WriteLine(result);

Outcome:

abcdef789

Remove all whitespace from string

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()
}

How do i remove all white spaces from a string?

Try this :

   images= images.Replace(" ", String.Empty);

Remove all whitespace in a string

If you want to remove leading and ending spaces, use str.strip():

>>> "  hello  apple  ".strip()
'hello apple'

If you want to remove all space characters, use str.replace() (NB this only removes the “normal” ASCII space character ' ' U+0020 but not any other whitespace):

>>> "  hello  apple  ".replace(" ", "")
'helloapple'

If you want to remove duplicated spaces, use str.split() followed by str.join():

>>> " ".join("  hello  apple  ".split())
'hello apple'

Strip all whitespace from a string

Here is some benchmarks on a few different methods for stripping all whitespace characters from a string: (source data):


BenchmarkSpaceMap-8 2000 1100084 ns/op 221187 B/op 2 allocs/op
BenchmarkSpaceFieldsJoin-8 1000 2235073 ns/op 2299520 B/op 20 allocs/op
BenchmarkSpaceStringsBuilder-8 2000 932298 ns/op 122880 B/op 1 allocs/op
  • SpaceMap: uses strings.Map; gradually increases the amount of allocated space as more non-whitespace characters are encountered
  • SpaceFieldsJoin: strings.Fields and strings.Join; generates a lot of intermediate data
  • SpaceStringsBuilder uses strings.Builder; performs a single allocation, but may grossly overallocate if the source string is mainly whitespace.
package main_test

import (
"strings"
"unicode"
"testing"
)

func SpaceMap(str string) string {
return strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return -1
}
return r
}, str)
}

func SpaceFieldsJoin(str string) string {
return strings.Join(strings.Fields(str), "")
}

func SpaceStringsBuilder(str string) string {
var b strings.Builder
b.Grow(len(str))
for _, ch := range str {
if !unicode.IsSpace(ch) {
b.WriteRune(ch)
}
}
return b.String()
}

func BenchmarkSpaceMap(b *testing.B) {
for n := 0; n < b.N; n++ {
SpaceMap(data)
}
}

func BenchmarkSpaceFieldsJoin(b *testing.B) {
for n := 0; n < b.N; n++ {
SpaceFieldsJoin(data)
}
}

func BenchmarkSpaceStringsBuilder(b *testing.B) {
for n := 0; n < b.N; n++ {
SpaceStringsBuilder(data)
}
}

How to remove all whitespace of a string in Dart?

Try this

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

Update:

String name = '4 ever 1 k g @@ @';
print(name.replaceAll(RegExp(r"\s+"), ""));

Another easy solution:

String name = '4 ever 1 k g @@ @';
print(name.replaceAll(' ', '');

Remove ALL white spaces from text

You have to tell replace() to repeat the regex:

.replace(/ /g,'')

The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.

If you want to match all whitespace, and not just the literal space character, use \s instead:

.replace(/\s/g,'')

You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:

.replaceAll(/\s/g,'')


Related Topics



Leave a reply



Submit