I have a column based txt file. How can I read any specific column programmatically?
So far I came up with this solution where it reads the specified column index for example: firstValue[0] will read all the (1) in the text file.
If I write it like this then I'll be able to read the first three index fine, but there has to be a cleaner approach.
Console.WriteLine(string.Join("", firstValue[0], firstValue1, firstValue[2], firstValue[3]));
If there was a way I could count the columns in the text file than pick the index of the column I want to read; that would be ideal.
I would like to read:
121
122
123
124
I've searched online for a similar problem, but they didn't quite have what I wanted.
string[] lines = File.ReadAllLines(YourFile);
foreach (var line in lines)
{
var firstValue = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[0];
Console.WriteLine(firstValue[0]);
//Console.WriteLine(string.Join("", firstValue[0], firstValue[1], firstValue[2], firstValue[3]));
}
Console.ReadKey();
You can try this one:
public static List<string> GetColumnValues(string[] lines, int columnNumber)
{
var result = new List<string>();
Regex regex = new Regex("[ ]{2,}", RegexOptions.None);
foreach (var line in lines)
{
var cleanedLine = regex.Replace(line, " ");
var columns = line.Split(" ", StringSplitOptions.RemoveEmptyEntries);
result.Add(columns[columnNumber-1]);
}
return result;
}
Additional checks should be added, but you can get an idea.
The problem was, splitting it like like this:
var firstValue = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
firstValue would equal a concatenated string something like this 121 20412 010 in the foreach loop
So then I tried another approach which was:
var firstValue = line.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
Which indexed the columns, so I can choose which column I want the data to come from.
foreach (var line in lines)
{
var firstValue = line.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(firstValue[2]);
}
Output:
010
020
030
040
Related
I want to read a text file and split the text file by removing delimiters and store it into two 1d-arrays (one for Movie name and other for Revenue)
Example of my text file:
Jurassic World=11734562.56
Black Panther#4352749.21
The Revenant}7452893.21
Trainwreck{1547892.45
May be this code, solve your problem. Splitfunction take chars and parse with these values. Delimeters are removed your result. If your all text like this (first name and delimeter and revenue), you can select even index as movie name and odd index as revenue.
string allText = #"Jurassic World=11734562.56
Black Panther#4352749.21
The Revenant}7452893.21
Trainwreck{1547892.45";
string[] splitStrings = allText.Split('\n', '=', '{', '}', '#');
string[] movies = splitStrings.Where((s, i) => i % 2 == 0).ToArray();
string[] revenues = splitStrings.Where((s, i) => i % 2 == 1).ToArray();
Another solution which strips unwanted chars.
string val = #" Jurassic World=11734562.56
Black Panther#4352749.21
The Revenant}7452893.21
Trainwreck{1547892.45";
string[] lines = val.Split('\r');
string[] movieNameArr = new string[lines.Length];
decimal[] amountsArr = new decimal[lines.Length];
for (int i = 0; i < lines.Length; i++)
{
string[] split = lines[i].Split(new Char[] { '=', '#', '}', '{' });
// replace new line or space chars with empty string
split[0] = Regex.Replace(split[0], #" |\n", string.Empty);
movieNameArr[i] = split[0];
amountsArr[i] = decimal.Parse(split[1]);
}
Console.WriteLine("Movie arr: [{0}]", string.Join(", ", movieNameArr));
Console.WriteLine("Amounts arr: [{0}]", string.Join(", ", amountsArr));
Console.ReadKey();
I have a string:
string data =
"item1 actived
item2 none
item special I none
item special II actived"
you can see 4 rows in the data.
I need to split a string into a List item as below:
item[0]={Name=item1, Status=actived}
item[1]={Name=item2, Status=none}
item[2]={Name=item Special I, Status=none}
item[3]={Name=item Special II, Status=actived}
I'm tried:
var s = SplitReturn(data);
public string[] SplitReturn(string name)
{
return name.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
}
How do I can Split space in my string and then convert to List?
string data =
#"item1 actived
item2 none
item special I none
item special II actived";
var result = data.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
.Select(item => {
int lastSpace = item.LastIndexOf(' ');
return new
{
Name = item.Substring(0, lastSpace).Trim(),
Status = item.Substring(lastSpace, item.Length - lastSpace).Trim()
}; }).ToList();
Here is the code and it is working fine for a single input string
string[] stop_word = new string[]
{
"please",
"try",
"something",
"asking",
"-",
"(", ")",
"/",
".",
"was",
"the"
};
string str = "Please try something (by) yourself. -befor/e asking";
foreach (string word in stop_word)
{
str = str.ToLower().Replace(word, "").Trim();
}
and the output is by yourself before
and now I want to have
string str[] = new string[]
{
"Please try something-by yourself. before (CAD) asking/",
"cover, was adopted. The accuracy (of) the- change map was"
};
and also may be the number of strings is greater than 2 then how to alter this above code to display the str array or store in a text file or database.
Please help with acknowledgements. Thanks
The code for single string need to be put inside a loop for string array
List<string> result = new List<string>();
for(int i =0; i<str.Length; i++)
{
foreach (string word in stop_word)
{
str[i] = str[i].ToLower().Replace(word, "").Trim();
str[i] = Regex.Replace(str[i], #"\s+", " ");
}
result.Add(str[i]);
}
foreach(string r in result)
{
//this is to printout the result
Console.WriteLine(r);
}
You can try it here: https://dotnetfiddle.net/wg83gM
EDIT:
Use regex to replace multiple spaces with one single space
Here is an easy to understand way to do it:
List<string> list = new List<string>();
foreach (string text in str)//loops through your str array
{
string newText =text;
foreach (string word in stop_word) //loops through your word array
{
newText = newText.ToLower().Replace(word, "").Trim();
}
list.Add(newText); //store the results in a list
}
Here is a working Demo
Does this work as you expect?
var results =
str
.Select(x => stop_word.Aggregate(x, (a, y) => a.ToLower().Replace(y, "").Trim()))
.ToArray();
I used this input:
string[] str = new string[]
{
"Please try something-by yourself. before (CAD) asking/",
"cover, was adopted. The accuracy (of) the- change map was"
};
string[] stop_word = new string[]
{
"please", "try", "something", "asking", "-", "(", ")", "/", ".", "was", "the"
};
I got this output:
by yourself before cad
cover, adopted accuracy of change map
You can use Select() for this.
var results = str.Select(x => {
foreach (string word in stop_word)
{
x = x.ToLower().Replace(word, "").Trim();
}
return x;
}).ToList(); // You can use ToArray() if you wish too.
...
foreach(string result in results)
{
Console.WriteLine(result);
}
Result:
by yourself before cad
cover, adopted accuracy of change map
I have a text file containing many lines which look like this:
Flowers{Tulip|Sun Flower|Rose}
Gender{Female|Male}
Pets{Cat|Dog|Rabbit}
I know how to read lines from a file, but what's the best way to split and store the categories and their subitems in a dictionary afterwards? Let's say from a string array which contains all the above lines?
The idea to use a regexp is right, but I prefer using named captures for readability
var regexp = new Regex(#"(?<category>\w+?)\{(?<entities>.*?)\}");
var d = new Dictionary<string, List<string>>();
// you would replace this list with the lines read from the file
var list = new string[] {"Flowers{Tulip|Sun Flower|Rose}"
, " Gender{Female|Male}"
, "Pets{Cat|Dog|Rabbit}"};
foreach (var entry in list)
{
var mc = regexp.Matches(entry);
foreach (Match m in mc)
{
d.Add(m.Groups["category"].Value
, m.Groups["entities"].Value.Split('|').ToList());
}
}
You get a dictionary with the category as a key, and the values in a list of strings
you can use the Key and value on this code
string T = #"Flowers{Tulip|Sun Flower|Rose}
Gender{Female|Male}
Pets{Cat|Dog|Rabbit}";
foreach (var line in T.Split('\n'))//or while(!file.EndOfFile)
{
var S = line.Split(new char[] { '{', '|','}' }, StringSplitOptions.RemoveEmptyEntries);
string Key = S[0];
MessageBox.Show(Key);//sth like this
for (int i = 1 ; i < S.Length; i++)
{
string value = S[i];
MessageBox.Show(value);//sth like this
}
}
you can use this:
string line = reader.ReadLine();
Regex r = new Regex(#"(\w+){(\w+)}");
now loop the results of this regex:
foreach(Match m in r.Matches(line)) {
yourDict.Add(m.Groups[1], m.Groups[2].Split(' '));
}
i am listbox to store different strings which user gives as input.
but i want to split those listbox items where i want to have the first word of every item as seperate string and rest as other string.
i am iterating the listbox item as
foreach (ListItem item in lstboxColumnList.Items)
{
column_name = temp + "\" "+item+"\"";
temp = column_name + "," + Environment.NewLine;
}
how could i get the splitted string
Assuming firs word ends with a space, you can use something like below:
string firsWord = sentence.SubString(0, sentence.IndexOf(' '));
string remainingSentence = sentence.SubString(sentence.IndexOf(' '), sentence.Length);
I dont know your listbox item's format..
but I assumed that your listbox item have at least 2 word and separate by a space..
so, you can do the splitting using substring and index of..
string first = sentence.SubString(0, sentence.IndexOf(" "));
string second = sentence.SubString(sentence.IndexOf(" ") + 1);
public void Test()
{
List<string> source = new List<string> {
"key1 some data",
"key2 some more data",
"key3 yada..."};
Dictionary<string, string> resultDictionary = source.ToDictionary(n => n.Split(' ').First, n => n.Substring(n.IndexOf(' ')));
List<string> resultStrings = source.Select(n => string.Format("\"{0}\",{1}", n.Split(' ').First, n.Substring(n.IndexOf(' ')))).ToList;
}
resultDictionary is a dictionary with the key set to the first word of each string in the source list.
The second closer matches the requirements in your question that it outputs a list of strings in the format you specified.
EDIT: Apologies, posted in VB first time round.
checkout:
var parts = lstboxColumnList.Items.OfType<ListItem>().Select(i => new {
Part1 = i.Text.Split(' ').FirstOrDefault(),
Part2 = i.Text.Substring(i.Text.IndexOf(' '))
});
foreach (var part in parts)
{
var p1 = part.Part1;
var p2 = part.Part2;
// TODO: use p1, p2 in magic code!!
}