简体   繁体   English

有没有从字符串中删除空格字符的方法?

[英]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? 是否有用于删除字符串中所有空格的string类成员函数(或其他)? Something like Python's str.strip() ? 像Python的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: 如果要删除所有空白字符,则可以使用Linq,即使该用例的语法不太吸引人也可以:

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

String.Trim method removes trailing and leading white spaces. String.Trim方法删除尾随空格和前导空格。 It is the functional equivalent of Python's strip method. 它在功能上等同于Python的strip方法。

LINQ feels like overkill here, converting a string to a list, filtering the list, then turning it back onto a string. 在这里,LINQ感觉有点过分了,将字符串转换为列表,过滤列表,然后将其转换回字符串。 For removal of all white space, I would go for a regular expression. 为了消除所有空白,我将使用正则表达式。 Regex.Replace(s, @"\\s", "") . 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. 如果您要根据.NET确定什么是空格来替换字符串中的所有空格(而不仅仅是开头和结尾的空格),则可以使用一个非常简单的LINQ查询使其起作用。

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() . 是的, String.Trim()

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

gives "ab" in result . "ab"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() . 如果要删除字符串中的所有空格,可以使用string.Replace()

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

gives "ab" in result . "ab"result But that is not equivalent to str.strip() in Python. 但这不等同于Python中的str.strip()

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... 我对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. 如果str.strip()仅在开头和结尾删除空格,则可以在.NET中使用str = str.Trim() ...否则,可以将str = str.Replace ( " ", "")用于删除所有空格。

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. string.Split默认沿char.IsWhiteSpace字符进行char.IsWhiteSpace因此,这与通过直接使用char.IsWhiteSpace过滤掉这些字符非常相似,并且在LINQ之前的环境中也可以使用。

你可以用

 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). 仅在搜索现有实现时才重要,但不要忘记对解决方案进行编程而不是搜索MSDN(无聊)是多么有趣。

You should be able to strip any chars from any string by using 1 of the 2 functions below. 您应该能够使用下面2个函数中的1个从任何字符串中去除所有字符。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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