Reputation: 147
Console.WriteLine("Insert the character you are searching for: ");
CharacterSearch = Console.ReadLine();
var count = file.Where(x => x == CharacterSearch).Count();
So what I am trying to do is to read text from the variable file
and then search for a specific character in the string that is entered from the keyboard. So the searched character would be CharacterSearch
.
I also want to check for their positions not just the number of occurrences.
Upvotes: 1
Views: 211
Reputation: 67898
This is very inefficient, but it's an option is the files are small.
CharacterSearch = Console.ReadKey();
var count = File.ReadLines(pathToFile)
.Select((c, i) => new { Character = c, Index = i })
.ToList()
.Where(x => x.Character == CharacterSearch);
Upvotes: 1
Reputation: 3183
Inefficient but can be applied if file is small.
public static int CharCount(string input,char c)
{
var charCount=input.GroupBy(a => a).ToDictionary(k => k.Key, v => v.Count());
if (charCount.ContainsKey(c))
return charCount[c];
return 0;
}
If you want to do the search over an over in the same string, i think it is better maintain a mapping. Again considerable only for a small file.
public static Dictionary<char, int> CharCountMapping(string input)
{
return input.GroupBy(a => a).ToDictionary(k => k.Key, v => v.Count());
}
Upvotes: 0
Reputation: 32481
Why not simply use this method? (Are you looking for a complicated one?)
List<int> indexes = new List<int>();
for (int i = 0; i < file.Length; i++)
{
if (file[i]==CharacterSearch)
{
indexes.Add(i);
}
}
int count = indexes.Count;
Upvotes: 1