'vb.net how to split text file
I have a file with the comma-separated lines as below:
PS23456789,08/2023,2011,LAM CHIUE MONG JP sdad,08/2023,2011,LAM CHIUE MONG JP xvczxcssf,08/2023,2011,LAM CHIUE MONG JP 42432,08/2023,2011,LAM CHIUE MONG JP fdsafs,08/2023,2011,LAM CHIUE MONG JP
I want to convert this data to fixed-length values and no commas, like this:
PS23456789 08/2023 2011 LAM CHIUE MONG JP sdad 08/2023 2011 LAM CHIUE MONG JP xvczxcssf 08/2023 2011 LAM CHIUE MONG JP 42432 08/2023 2011 LAM CHIUE MONG JP fdsafs 08/2023 2011 LAM CHIUE MONG JP
Unfortunately, I can only get the first row to look right. The others do not work. Here is what it looks like:
PS23456789 08/2023 2011 LAM CHIUE MONG JP sdad08/2023 2011 LAM CHIUE MONG JP xvczxcssf08/2023 2011 LAM CHIUE MONG JP 4243208/2023 2011 LAM CHIUE MONG JP fdsafs08/2023 2011 LAM CHIUE MONG JP
This is my code:
Dim splitFile = File.ReadAllText(Result).Split(",")
For count = 0 To splitFile.Length - 1
While (splitFile(count).Length < 20)
splitFile(count) = splitFile(count) + " "
End While
totalFile += splitFile(count)
Next
My.Computer.FileSystem.WriteAllText("C:test.txt", totalFile, False)
How can I fix this?
Solution 1:[1]
I think that's because you are reading all the lines as a whole. The end of each line should be a \n symbol, thus the last string of the first line cannot be separated with the first string of the second line. The concatenated string is longer than the length you have defined (i.e. 20), therefore no space is added. You should read the file line by line and process each line separately.
BTW, to add trailing spaces to get fixed length strings, you may want to try String.Format which performs much better.
Check ref here. Example:
String.Format({0:-20}, splitFile(count))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
