I have a file consisting of two columns that will be stored as a Dictionary where the first column will be the key, and the second column will be the value. The second column is delimited by whitespace, which may be any amount of spaces or tabs.
How do I store this in my Dictionary with the Split() function?
recipesFile = new StreamReader(recipesRes.Stream);
char[] splitChars = {'\t', ' '};
while (recipesFile.Peek() > 0)
{
string recipesLine = "";
recipesLine = recipesFile.ReadLine();
string[] recipesInLine = recipesLine.Split(splitChars);
recipes.Add(recipesInLine[0], recipesInLine[1]);
}
Thanks
recipesLine.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
Also your code in general can be shortened to
var myDictionary = File.ReadLines(myFileName)
.Select(l => l.Split(new []{'\t', ' '}, StringSplitOptions.RemoveEmptyEntries))
.ToDictionary(a => a[0], a => a[1]);
Since your entries are separated using multiple whitespace characters and Split splits on single characters, you need to remove empty entries. There's a separate String.Split overload for that purpose:
string[] recipesInLine = recipesLine.Split(splitChars,
StringSplitOptions.RemoveEmptyEntries);
firstly, use the file.readlines method. then you can use linq over the lines. http://msdn.microsoft.com/en-us/library/dd383503.aspx
Jon Skeet and Marc Gravell both have good examples on using linq to read files here,
Reading a file line by line in C#.
Then use ToDictionary - Yuriy's answer is a good solution.
Related
I have a String example:
#5/r/n#12/r/n#23/r/n#43/r/n#54/r/n#23/r/n#77/r/n
I need to pass these values to a list and get the values between # and /r/n
So far I have the following code:
List<string> result = Regex.Split(String, #"/r/n").ToList();
This separates each value, leaving #, how can I remove #, to each value from the list?
You can do this in one line using LINQ:
List<string> result = Regex.Split(String, #"/r/n").Select(s => s.Replace("#", "")).ToList();
You can use the trim function to remove special characters from the front and end of your strings.
myString.Trim( new Char[] { '#', ' '} )
User the string null or empty operator to cleanse any empty strings as well:
List<string> result = Regex.Split(myString, #"/r/n").Select(a => a.Trim(new Char[] { '#', ' ' })).Where(b => !String.IsNullOrEmpty(b)).ToList();
You can use trim
char[] charsToTrim = { '#' };
List<string> result = Regex.Split(String, #"/r/n").
.Select(x => x.Trim(charsToTrim))
.ToList();
You could also split on the # and trim the other. Which ever makes sense.
I believe that Trim will be faster than Replace -- but I did not test it.
I am trying to take a string of numbers each separated by a space, and turn it into a list. The user inputs the string of numbers by typing a number, then a space, as needed. This goes into "myString." I want to take the string and take just the numbers, and add it to myList. The code I want to create is something like this:
for(int i = 0; i < myString.Length; i++)
{
//If its not a space, add it to the list
if (myString[i] != " ")
{
myList.Add(prices[i]);
}
}
The error however says that you cannot use the '!=' operator to the types char, and string. Makes sense, but I am having a hard time finding an alternative. Is there a more efficient way to turn a string of: "1 2 3 4 5" into a List?
This is for the google jams code challenge, as I am just practicing on old questions. The link can be found here:
https://code.google.com/codejam/contest/351101/dashboard#s=p0
Thank you for all the help guys! I'm always amazed at how helpful SO is for High School programmers like me who still really have no clue what they're doing :-)
Use Split method instead
var numbers = myString.Split().Select(x => int.Parse(x)).ToArray();
BTW,in order to represent a char constant single quotes are used in C#. So as already mentioned in the comments, " " is a string literal that contains a space not a char.You should use ' '
Two things:
First, to fix your error change your line to:
if (myString[i] != ' ') // change to single quotes.
Second, there is an easier way:
string.Split(new char[] {' '}); // this will return the array you're seeking...
myString[i] is a char, so instead of " " you should use ' ' single quotes.
You can use the String.Split method to split the string on the spaces, resulting in a list of stirngs representing the numbers.
myList = myString.Split(" ");
You need to split your string on space. You can use LINQ like:
List<int> list = myString.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse)
.ToList();
If you want a safer option and replace any invalid entry to -1 you can use int.TryParse like:
int temp;
List<int> list = myString.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
.Select(r => { return int.TryParse(r, out temp) ? temp : -1; })
.ToList();
I'm trying to filter a collection of strings by a "filter" list... a list of bad words. The string contains a word from the list I dont want it.
I've gotten so far, the bad Word here is "frakk":
string[] filter = { "bad", "words", "frakk" };
string[] foo =
{
"this is a lol string that is allowed",
"this is another lol frakk string that is not allowed!"
};
var items = from item in foo
where (item.IndexOf( (from f in filter select f).ToString() ) == 0)
select item;
But this aint working, why?
You can use Any + Contains:
var items = foo.Where(s => !filter.Any(w => s.Contains(w)));
if you want to compare case-insensitively:
var items = foo.Where(s => !filter.Any(w => s.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0));
Update: If you want to exlude sentences where at least one word is in the filter-list you can use String.Split() and Enumerable.Intersect:
var items = foo.Where(sentence => !sentence.Split().Intersect(filter).Any());
Enumerable.Intersect is very efficient since it uses a Set under the hood. it's more efficient to put the long sequence first. Due to Linq's deferred execution is stops on the first matching word.
( note that the "empty" Split includes other white-space characters like tab or newline )
The first problem you need to solve is breaking up the sentence into a series of words. The simplest way to do this is based on spaces
string[] words = sentence.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
From there you can use a simple LINQ expression to find the profanities
var badWords = words.Where(x => filter.Contains(x));
However this is a bit of a primitive solution. It won't handle a number of complex cases that you likely need to think about
There are many characters which qualify as a space. My solution only uses ' '
The split doesn't handle punctuations. So dog! won't be viewed as dog. Probably much better to break up words on legal characters
The reason your initial attempt didn't work is that this line:
(from f in filter select f).ToString()
evaluates to a string of the Array Iterator type name that's implied by the linq expression portion. So you're actually comparing the characters of the following string:
System.Linq.Enumerable+WhereSelectArrayIterator``2[System.String,System.String]
rather than the words of the filter when examining your phrases.
I am trying to split a string into a string[] made of the words the string originally held using the fallowing code.
private string[] ConvertWordsFromFile(String NewFileText)
{
char[] delimiterChars = { ' ', ',', '.', ':', '/', '|', '<' , '>','/','#','#','$','%','^','&','*','"','(',')',';'};
string[] words = NewFileText.Split(delimiterChars);
return words;
}
I am then using this to add the words to a dictionary that keeps up with word keys and their frequency value. All other duplicated words are not added as keys and only the value is affected. However the last word is counted as a different word and is therefore made into a new key. How can i fix this?
This is the code I have for adding words to the dictionary :
public void AddWord(String newWord)
{
newWord = newWord.ToLower();
try
{
MyWords.Add(newWord, 1);
}
catch (ArgumentException)
{
MyWords[newWord]++;
}
}
To clarify the problem i am having is that even if the word at the end of a string is a duplicate it is still treated like a new word and therefore a new string.
Random guess - space at the end makes empty word that you don't expect. If yes - use correct option for Split:
var words = newFileText.Split(delimiterChars,
StringSplitOptions.RemoveEmptyEntries);
Split is not the best choice to do what you want to do because you end having this kind of problems and you also have to specify all the delimiters, etc.
A much better option is using a regular expressions instead of your ConvertWordsFromFile method as follow:
Regex.Split(theTextToBeSplitted, #"\W+")
This line will return an array containing all the 'words'. Once you have that, the next step should be create your dictionary so, if you can use linq in your code, the easiest and cleaner way to do what you want is this one:
var theTextToBeSplitted = "#Hi, this is a 'little' test: <I hope it is useful>";
var myDictionary = Regex.Split(theTextToBeSplitted, #"\W+")
.GroupBy(x => x)
.ToDictionary(x => x.Key, x => x.Count());
That´s all that you need.
Good luck!
my double data in text file like below:
1.4 2.3 3.4
2.2 2.5 2.5
I want simply read this data from file
and store it in an array.
please help me.
I'm a beginner in C#
You can use LINQ:
double[] numbers =
File.ReadAllLines(path)
.Select(s => double.Parse(s)
.ToArray()
If each line can have multiple numbers, you'll need to split the lines:
double[] numbers =
File.ReadAllLines(path)
.SelectMany(s => s.Split(' '))
.Select(s => double.Parse(s)
.ToArray()
You can also use a normal loop:
List<double> numbers = new List<double>();
foreach(string line in File.ReadAllLines(path)) {
numbers.Add(Double.Parse(line));
}
Or, to split them,
List<double> numbers = new List<double>();
foreach(string line in File.ReadAllLines(path)) {
foreach(string word in line.Split(' ') {
numbers.Add(Double.Parse(word));
}
}
Consult MSDN with the following pointers...
File class to read the file contents as string
String.Split to split the numbers based on your delimited
and Double.Parse to convert from string into double.
var values = from value in File.ReadAllText("C:\\Yourfilename.txt").Split(' ')
select double.Parse(value);
Try this, it should be somewhat more bulletproof than some of the other answers. It does not check for invalid data entries which can't be parsed correctly.
var doubles = File.ReadAllText(path)
.Split(new[] {" ", "\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => double.Parse(s, CultureInfo.GetCultureInfo("en-US"))).ToArray();
This will work if the doubles are splitted by either a space or a line break. And it also works if there are multiple spaces/line breaks. I live in DK so I have setted the culture info explicit for parsing.