开发者

how replace all spaces in a text file with one character?

i have a text file like below :

string string
string                 string
string   string
string          string

i want to replace all these spaces with pipe (|) character.

is the开发者_开发知识库re any method in c# for doing that?

i am using the below codes for read and write on file :

How do I read and edit a .txt file in C#?

EDIT:

after using the codes in the accepted answer i got the below error in line of

System.IO.File.WriteAllLines( ...:

Could not find file 'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\infilename.txt'.

[Solves by absolute path]

thanks for comments and answers :

not each space with one pipe -> all spaces in each line with one pipe...

thanks in advance


Change the aanund's answer in:

System.IO.File.WriteAllLines(
    "outfilename.txt",
    System.IO.File.ReadAllLines("infilename.txt").Select(line =>
        string.Join("|",
            line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
        )
    ).ToArray()
);


Something like this should work:

System.IO.File.WriteAllLines(
    "outfilename.txt",
    System.IO.File.ReadAllLines("infilename.txt").Select(line =>
        System.Text.RegularExpression.Regex.Replace(line, @"\s+", "|")
        )
    ).ToArray()
);  

Note I just copied from the link and changed it to search for whitespace and replace that with a pipe.


This might be what you are looking for

var regex = new Regex("[ ]+", RegexOptions.Compiled);
regex.Replace(inputString, replaceCharacter);

after you read the whole file, use this regex and write it back into your file.


You can try using regex:

string text = "test    test   test         test";
string cleanText = System.Text.RegularExpressions.Regex.Replace(text, @"\s+", "|");


Using Just Replace:

      string original  = "test   test  test test";
      string formatted = original.Replace("  ", " ").Replace(" ", "|");

replace all occurrences of 2 adjacent spaces with just 1 space, then replace the final space with the pipe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜