Parse text inbetween tabs - c#

I have to copy and paste excel into a form and extract each value and since it's separated by tabs I'm doing something like:
var lines = PasteText.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
foreach (var currLine in lines.Where(x => !String.IsNullOrWhiteSpace(x)))
{
var items = currLine.Split(new string[] { "\t", " " }, StringSplitOptions.RemoveEmptyEntries)
.Take(15).ToArray();
}
But a problem arises if there's a tab inside one of the column fields.
How could I go about solving this?

Related

Split String with multiple delimiters to different arrays in c#

So I have a text file copied into memory that is delimited as follows:
"425,9856\n852,9658\n"
This is a long string with some 30,000 entries in total. What I want to do is create two arrays, one for the value to the left of the comma, one for the value to the right of the comma, and then to each array respectively i want to append the next two comma delimited strings that come after the "\n".
I have tried splitting using .Split and passing two delimiting values, but it obviously just creates one array with all values sequentially. Such as:
425
9856
852
9658
When what I want is:
array1:
452
852
array2:
9856
9658
Does that make sense?
many thanks
Since you're reading from a file, why not stream the input line-by-line, rather than reading the whole lot into memory in one go?
using var reader = new StreamReader(filePath);
while (reader.ReadLine() is not null line)
{
// Each line is of the form '425,9856', so just split on the comma
var parts = line.Split(',');
firstList.Add(parts[0]);
secondList.Add(parts[1]);
}
You can just split it twice to get what you want
public static void Main()
{
var foo = "425,9856" + Environment.NewLine + "852,9658" + Environment.NewLine;
var array1 = new List<string>();
var array2 = new List<string>();
string[] lines = foo.Split(
new string[] { Environment.NewLine },
StringSplitOptions.None);
foreach(var line in lines)
{
//Console.WriteLine("line: " + line);
var lineSplit = line.Split(',');
//Console.WriteLine("lineSplit: " + lineSplit.Length);
//lineSplit.Dump();
if(lineSplit.Length > 1)
{
array1.Add(lineSplit[0]);
array2.Add(lineSplit[1]);
}
}
Console.WriteLine("Array1: ");
array1.Dump();
Console.WriteLine("Array2: ");
array2.Dump();
}
And here's a working fiddle of it.
You can use RegEx
string row = #"425,9856\n852,9658\n";
string left = #"[^|(?<=n)]\d*(?=,)";
string right = #"(?<=,)\d*(?=\\)";
Regex rgLeft = new Regex(left);
var l = rgLeft.Matches(row).Select(p=> p.Value);
Regex rgRight = new Regex(right);
var r = rgRight.Matches(row).Select(p=> p.Value);

DataGridView creates extra lines when I import a text file into it.

I'm trying to import a .txt file to a DataGrid. The problem is although the code works mostly OK, when import the .txt file, it creates to extra lines, something like this;
OpenFileDialog ofd = new OpenFileDialog();
ofd.DefaultExt = ".txt";
ofd.InitialDirectory = #"C:\Users\Cabbaa\Desktop";
DialogResult a = ofd.ShowDialog();
var lines = File.ReadAllLines(ofd.FileName);
if (lines.Count() > 0)
{
foreach (var columnName in lines.FirstOrDefault()
.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries))
{
dataGridView1.Rows.Add(Time, Class);
}
foreach (var cellValues in lines)
{
var cellArray = cellValues
.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
if (cellArray.Length == dataGridView1.Columns.Count)
dataGridView1.Rows.Add(cellArray);
}
}
Your problem lies in the first foreach loop of your code.
//you are adding rows to the column here, you are not adding headers
foreach (
var columnName in
lines.FirstOrDefault().Split(new[] {','},
StringSplitOptions.RemoveEmptyEntries)
)
{
//since we split the line on commas,
//we are adding a row to the table for every
//CSV value we found in the current line.
//this is causing the "garbage" rows you are seeing
//i do not know where "Time" and "Class" come from here.
//they weren't part of that first line in this example.
//my guess is you do not need this loop at all.
//since the headers already neatly show up on the table in your screenshot.
dataGridView1.Rows.Add(Time, Class);
}
//this works just fine.
foreach (var cellValues in lines)
{
var cellArray = cellValues
.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
if (cellArray.Length == dataGridView1.Columns.Count)
dataGridView1.Rows.Add(cellArray);
}

How can i use multiple delimiters in Array List

I want to ask you about the below code:
string[] seledCats = new string[0];
string condsCats = EzCoding.Web.UI.QueryStringParsing.GetValue(
"CondsCats",
EzCoding.Web.RequestMethod.Post);
if (condsCats != null)
{
seledCats = condsCats.Split(new string[] { "," },
StringSplitOptions.RemoveEmptyEntries);
}
After insert the selected data in the array list, output like that A1,A2,
But I want to show it like that this one 'A1','A2'
So, How can i do it ?
Thanks.
You can use this little LINQ query:
string condsCats = EzCoding.Web.UI.QueryStringParsing.GetValue("CondsCats",EzCoding.Web.RequestMethod.Post);
string[] seledCats = null;
if(condsCats != null)
seledCats = condsCats
.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => String.Format("'{0}'", s))
.ToArray();
seledCats = condsCats.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
string s = "'" + string.Join("','", seledCats) + "'";
//to split into array again...
seledCats = condsCats.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

Convert from 'string' to 'System.Collections.Generic.IEnumerable<string>

Here is my code :
var query = System.IO.File.ReadLines(#"c:\temp\mytext.txt")
.Select(line => line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0]);
System.IO.File.WriteAllLines(#"c:\temp\WriteLines.txt", query);
I want to convert quert to string so I can edit it , like this code for example
string[] res = s.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
I can use res[0].Substring and res[0].PadRight many options in text
So how can I convert my first code to become string but do same function?
I'm assuming that your file looks like this (Like grid):
Text11 Text12 Text13 Text14
Text21 Text22 Text23 Text24
Text31 Text32 Text33 Text34
Now you want to split it by cells so:
var query = System.IO.File.ReadLines(#"c:\temp\mytext.txt")
.Select(line => line.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries)).ToList();
Now when you writing this back to the file you should join the lines:
System.IO.File.WriteAllLines(#"c:\temp\WriteLines.txt", query.Select(line => String.Join(" ", line)));
And when you want to edit cell you can use:
query[row][column].Substring();
You can simply add .ToArray() at the end :
var query = System.IO.File.ReadLines(#"c:\temp\mytext.txt")
.Select(line => line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0])
.ToArray();
So you can do like query[0].Substring and query[0].PadRight.
Is that what you want?

Adding a Newline

The code below adds the characters \r\n to my string variable but once the string is returned the Newline is ignored.
Here is a snippet of the returned string: Mondavi\r\nrms_processtype
And here is the code where I add a Newline:
char[] charsToTrim = { ',', ' ' };
feed = feed.TrimEnd(charsToTrim) + Environment.NewLine;
Here's the code that error's when it attempts to read the "feed" variable
var dict = feed.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)
.SelectMany(s => s.Split('|')).ToDictionary(t => t.Split(',')[0], t => t.Split(',')[1]);
Try StringSplitOptions.RemoveEmptyEntries

Categories