Home > OS >  Splitting of string and how to join afterward lines?
Splitting of string and how to join afterward lines?

Time:09-25

I have a text file in which address are written in a manner i.e.

>
8,SENT VILA,
BESIDE GREEN RESIDANSY,MJ
>
10/787, BRUNSITK
PEL ROAD,
SEM TIC 7840
>
2/4596,
MAIN ROAD,
10/787, PAL
PEL ROAD,
SEM TIC 7840

when I split string with '>', it gives all result in an arry.

Here is my code..

var x = File.ReadAllText(text file path);
var y = x.Split(x,StringSplitOptions.None);
var z = string.Join("", y.ToArray());
        Console.WriteLine(z);

What I want to do is split with '>' and Join the lines with space as a separator below.

i.e.

  • 8,SENT VILA,BESIDE GREEN RESIDANSY,MJ
  • 10/787, BRUNSITK PEL ROAD, SEM TIC 7840

Any ideas? I tried searching plenty of questions, but is not like this one.

CodePudding user response:

I think you should read the file as an array:

var a = File.ReadAllLines(path);

Then you can drop the '>' by LINQ "where line not startswith >" when you join with space:

var r = string.Join(" ", a.Where(line => !line.StartsWith(">")))

There is some inconsistency in your input, your desire and your example output; for example the address with PAL seems to have disappeared from the expected output, and you didn't put a space between VILA, and BESIDE but did put one between BRUNSITK and PEL and also between ROAD, and SEM.

I don't really know how to rationalize these, but I'm sure you can ¯\_(ツ)_/¯


Edit, in response to question edit..

OK, so how about reading the file, splitting on > then removing the line breaks:

var addresses = File.ReadAllText(path)
  .Split('>')
  .Select(e => e.Replace("\r\n"," "))

If the file lines are terminated by just \n, adjust the replacement..

If you just want a single string out maybe the simplest thing is a double replacement :

var s = File.ReadAllText(path).Replace("\r\n"," ").Replace(">", "\r\n")

i.e. remove ALL the line breaks and then change the > to line breaks..

  •  Tags:  
  • c#
  • Related