Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 消除字符串中的空格,除非它们位于文字引号中_C#_Winforms - Fatal编程技术网

C# 消除字符串中的空格,除非它们位于文字引号中

C# 消除字符串中的空格,除非它们位于文字引号中,c#,winforms,C#,Winforms,我正在使用windows窗体和c#进行一个项目。在这个项目中,我需要获取一个字符串,并将其转换为一个新的字符串,该字符串删除了所有空格,除非它们周围有literal* 我已经设法消除了所有其他类型的空白(制表符、cr、新行)。对于这个问题,我只讨论空格键中的空格。我曾想过使用一种方法或循环,我尝试了几种不同的方法,但没有成功。任何帮助都将不胜感激。提前谢谢你,卡森 例如: string myString = "this is a test *a b c*this is a test*1 2 3*

我正在使用windows窗体和c#进行一个项目。在这个项目中,我需要获取一个字符串,并将其转换为一个新的字符串,该字符串删除了所有空格,除非它们周围有literal*

我已经设法消除了所有其他类型的空白(制表符、cr、新行)。对于这个问题,我只讨论空格键中的空格。我曾想过使用一种方法或循环,我尝试了几种不同的方法,但没有成功。任何帮助都将不胜感激。提前谢谢你,卡森

例如:

string myString = "this is a test *a b c*this is a test*1 2 3* this is a test";
// through some method or loop would return this:
string newString = "thisisatest*a b c*thisisatest*1 2 3*thisisatest"
// notice how the spaces remain when they are in literal quotes

只需在字符之间循环并保留一个标志,当您看到双引号时可以切换该标志,并使用该标志确定是否保留空格

bool quoted = false;
var builder = new StringBuilder();
foreach(char c in myString) {
    if(!quoted && c == ' ')
        continue;
    if(c == '"')
        quoted = !quoted;
    builder.Append(c);
}

myString = builder.ToString();

谢谢,我知道事情就是这么简单。我的类似,但不起作用。再次感谢。