删除复杂字符串中的空格

Deleting Spaces In Complicated Strings

关于在长而复杂的字符串中删除 spaces 的另一个愚蠢的新手问题(就像孔子说的那样,最好问而不是生活在无知中)。首先,我必须说我正在尝试做这本书中的练习:C# 7.0: All-In-One-For-dummies 以及我从这本书中获取的以下示例。这是代码:

internal class Program
    {
        static void Main(string[] args)
        {
            string someString = " this is a\nstring. ";
            char[] whiteSpace = {' ', '\n', '\t' };
            Console.WriteLine("Here is how the string looks before:" + someString);
            Console.WriteLine("And here is how it looks after: ");
            for( ; ; )
            {
                int offset = someString.IndexOfAny(whiteSpace);
                if (offset == -1)
                {
                    break;
                }
                string before = someString.Substring(0, offset);
                string after = someString.Substring(offset + 1);
                someString = string.Concat(before, after);
            }
            Console.WriteLine(someString);

            Console.WriteLine("\nPress any key to terminate the program. ");
            Console.ReadLine();
        }
    } 

输出是这样的:“thisisastring”但是为什么呢?任何人都可以解释一下吗? 在后面连接两个子字符串(“之前”和“之后”)的行之前,一切看起来都很容易理解。为什么无限循环删除所有 spaces?据我所知,Substring() 方法不会删除任何内容,Concat() 也是如此。变量“before”是 space 之前的部分,变量“after”是 space 之后的部分。程序在哪一刻删除了space?

提前感谢您的任何建议!

before字符串是空白字符之前的字符串,after字符串是空白字符之后的字符串,两者都排除了空白字符,所以新字符串是与前面相同,删除了空白字符。这就是为什么最终结果没有任何空白字符的原因。

该程序不会在物理上“删除 space”。这一行:

someString = string.Concat(before, after);

做两件事:

  1. 取之前和之后的子字符串并将它们连接起来,得到一个字符串类型的新值(从 Concat 函数返回的值)。
  2. 将该新值赋值给现有的字符串变量 someString。因此,存储在 someString 中的先前值(包含 spaces)被丢弃,并由这个新值替换。

让我试着解释一下:

...
// Infinite loop; common alternative form is "while (true) {...}" 
for( ; ; )
{
    // looking for the leftmost index of any char from whiteSpace array
    int offset = someString.IndexOfAny(whiteSpace);
    
    // if no whitespace found ...
    if (offset == -1)
    {
        // ... stop processing the string
        break;
    }
    
    // from now on offset is the index of the leftmost whitespace character 

    // we remove leftmost whitespace character: someString = before + after
    // note, that before is a substring before whitespace; 
    // after is a substring after whitespace

    // before - we take all characters in [0..offset) range; 
    // note, that char at offset index - i.e. whitespace character - is excluded
    string before = someString.Substring(0, offset);

    // after - we take all characters starting from offset + 1 -
    // again we don't take whitespace character  which is at offset index 
    string after = someString.Substring(offset + 1);

    // finally, we combine all characters except the leftmost whitespace,
    // i.e. character which is on offset index
    someString = string.Concat(before, after);
}
...