简体   繁体   中英

Is there a method for removing whitespace characters from a string?

Is there a string class member function (or something else) for removing all spaces from a string? Something like Python's str.strip() ?

You could simply do:

myString = myString.Replace(" ", "");

If you want to remove all white space characters you could use Linq, even if the syntax is not very appealing for this use case:

myString = new string(myString.Where(c => !char.IsWhiteSpace(c)).ToArray());

String.Trim method removes trailing and leading white spaces. It is the functional equivalent of Python's strip method.

LINQ feels like overkill here, converting a string to a list, filtering the list, then turning it back onto a string. For removal of all white space, I would go for a regular expression. Regex.Replace(s, @"\\s", "") . This is a common idiom and has probably been optimized.

如果要删除字符串前面或结尾的空格,则可能需要查看TrimStart()和TrimEnd()和Trim()。

If you're looking to replace all whitespace in a string (not just leading and trailing whitespace) based on .NET's determination of what's whitespace or not, you could use a pretty simple LINQ query to make it work.

string whitespaceStripped = new string((from char c in someString
                                        where !char.IsWhiteSpace(c)
                                        select c).ToArray());

Yes, Trim.

String a = "blabla ";
var b = a.Trim(); // or TrimEnd or TrimStart

Yes, String.Trim() .

var result = "   a b    ".Trim();

gives "ab" in result . By default all whitespace is trimmed. If you want to remove only space you need to type

var result = "   a b    ".Trim(' ');

If you want to remove all spaces in a string you can use string.Replace() .

var result = "   a b    ".Replace(" ", "");

gives "ab" in result . But that is not equivalent to str.strip() in Python.

There are many diffrent ways, some faster then others:

public static string StripTabsAndNewlines(this string s) {

    //string builder (fast)
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < str.Length; i++) {
        if ( !  Char.IsWhiteSpace(s[i])) {
            sb.Append();
        }
    }
    return sb.tostring();

    //linq (faster ?)
    return new string(input.ToCharArray().Where(c => !Char.IsWhiteSpace(c)).ToArray());

    //regex (slow)
    return Regex.Replace(s, @"\s+", "")

}

I don't know much about Python...

IF the str.strip() just removes whitespace at the start and the end then you could use str = str.Trim() in .NET... otherwise you could just str = str.Replace ( " ", "") for removing all spaces.

IF it removes all whitespace then use

str = (from c in str where !char.IsWhiteSpace(c) select c).ToString()

I'm surprised no one mentioned this:

String.Join("", " all manner\\tof\\ndifferent\\twhite spaces!\\n".Split())

string.Split by default splits along the characters that are char.IsWhiteSpace so this is a very similar solution to filtering those characters out by the direct use of char.IsWhiteSpace and it's a one-liner that works in pre-LINQ environments as well.

你可以用

 StringVariable.Replace(" ","")

Strip spaces? Strip whitespaces? Why should it matter? It only matters if we're searching for an existing implementation, but let's not forget how fun it is to program the solution rather than search MSDN (boring).

You should be able to strip any chars from any string by using 1 of the 2 functions below.

You can remove any chars like this

static string RemoveCharsFromString(string textChars, string removeChars)
{
    string tempResult = "";
    foreach (char c in textChars)
    {
        if (!removeChars.Contains(c))
        {
            tempResult = tempResult + c;
        }
    }
    return tempResult;
}

or you can enforce a character set (so to speak) like this

static string EnforceCharLimitation(string textChars, string allowChars)
{
    string tempResult = "";
    foreach (char c in textChars)
    {
        if (allowChars.Contains(c))
        {
            tempResult = tempResult + c;
        }
    }

    return tempResult;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM