Fastest way to remove white spaces in string

后端 未结 13 1110
粉色の甜心
粉色の甜心 2020-11-27 18:39

I\'m trying to fetch multiple email addresses seperated by \",\" within string from database table, but it\'s also returning me whitespaces, and I want to remove the whitesp

相关标签:
13条回答
  • 2020-11-27 18:52

    With linq you can do it simply:

    emailaddress = new String(emailaddress
                                         .Where(x=>x!=' ' && x!='\r' && x!='\n')
                                         .ToArray());
    

    I didn't compare it with stringbuilder approaches, but is much more faster than string based approaches. Because it does not create many copy of strings (string is immutable and using it directly causes to dramatically memory and speed problems), so it's not going to use very big memory and not going to slow down the speed (except one extra pass through the string at first).

    0 讨论(0)
  • 2020-11-27 18:54

    Fastest and general way to do this (line terminators, tabs will be processed as well). Regex powerful facilities don't really needed to solve this problem, but Regex can decrease performance.

    new string
        (stringToRemoveWhiteSpaces
           .Where
           (
             c => !char.IsWhiteSpace(c)
           )
           .ToArray<char>()
        )
    
    0 讨论(0)
  • 2020-11-27 18:56

    You should try String.Trim(). It will trim all spaces from start to end of a string

    Or you can try this method from linked topic: [link]

        public static unsafe string StripTabsAndNewlines(string s)
        {
            int len = s.Length;
            char* newChars = stackalloc char[len];
            char* currentChar = newChars;
    
            for (int i = 0; i < len; ++i)
            {
                char c = s[i];
                switch (c)
                {
                    case '\r':
                    case '\n':
                    case '\t':
                        continue;
                    default:
                        *currentChar++ = c;
                        break;
                }
            }
            return new string(newChars, 0, (int)(currentChar - newChars));
        }
    
    0 讨论(0)
  • 2020-11-27 18:57

    Given the implementation of string.Replaceis written in C++ and part of the CLR runtime I'm willing to bet

    email.Replace(" ","").Replace("\t","").Replace("\n","").Replace("\r","");

    will be the fastest implementation. If you need every type of whitespace, you can supply the hex value the of unicode equivalent.

    0 讨论(0)
  • 2020-11-27 18:57

    Please use the TrimEnd() method of the String class. You can find a great example here.

    0 讨论(0)
  • 2020-11-27 18:57
    string str = "Hi!! this is a bunch of text with spaces";
    
    MessageBox.Show(new String(str.Where(c => c != ' ').ToArray()));
    
    0 讨论(0)
提交回复
热议问题