如何从文本文件中删除空格并将其替换为分号?

beh*_*aqi 2 c#

我将这些数据放入测试文本文件中:

behzad  razzaqi  xezerlooot   abrizii         ast
Run Code Online (Sandbox Code Playgroud)


我想删除空格并将空格替换为一个分号字符,在c#中写入此代码:

string[] allLines = File.ReadAllLines(@"d:\test.txt");
            using (StreamWriter sw = new StreamWriter(@"d:\test.txt"))
            {
                foreach (string line in allLines)
                {
                    if (!string.IsNullOrEmpty(line) && line.Length > 1)
                    {
                        sw.WriteLine(line.Replace(" ", ";"));
                    }
                }
            }
            MessageBox.Show("ok");
Run Code Online (Sandbox Code Playgroud)


behzad;;razzaqi;;xezerlooot;;;abrizii;;;;;ast
Run Code Online (Sandbox Code Playgroud)


但我想在太空中使用一个分号.我可以解决这个问题吗?

Sae*_*ini 6

正则表达式是一个选项:

string[] allLines = File.ReadAllLines(@"d:\test.txt");
using (StreamWriter sw = new StreamWriter(@"d:\test.txt"))
{
    foreach (string line in allLines)
    {
        if (!string.IsNullOrEmpty(line) && line.Length > 1)
        {
            sw.WriteLine(Regex.Replace(line,@"\s+",";"));
        }
    }
}
MessageBox.Show("ok");
Run Code Online (Sandbox Code Playgroud)