我的代码发布在下面。我希望它输出输入文件中#
个字符的数量。它目前没有提供预期的输出。
static void Main(string[] args)
{
StreamReader oReader;
if (File.Exists(@"C:\Documents and Settings\9chat73\Desktop\count.txt"))
{
Console.WriteLine("Enter a word to search");
string cSearforSomething = Console.ReadLine().Trim();
oReader = new StreamReader(@"C:\Documents and Settings\9chat73\Desktop\count.txt");
string cColl = oReader.ReadToEnd();
string cCriteria = @"\b" + cSearforSomething + @"\b";
System.Text.RegularExpressions.Regex oRegex = new System.Text.RegularExpressions.Regex(cCriteria, RegexOptions.IgnoreCase);
int count = oRegex.Matches(cColl).Count;
Console.WriteLine(count.ToString());
}
Console.ReadLine();
}
每次输出为0。我将以下文件作为count.txt:00100324103| #00100324137| #00100324145| #00100324153| #00100324179|
。我想计算文件中的哈希数(#)。怎么做。
答案 0 :(得分:3)
您正在寻找#作为单独的单词。从您的标准中删除字边界要求:
string cCriteria = cSearforSomething;
答案 1 :(得分:0)
试试上面的
int count = cColl.Count(x => x == '#');
var count = File.ReadAllText(@"c:\...").Count(x => x == '#');
答案 2 :(得分:0)
问题在于'#'(您要查找的符号)是正则表达式中的特殊符号 所以,应该转义:
static void Main(string[] args) {
//String fileName = @"C:\Documents and Settings\9chat73\Desktop\count.txt";
// To search dinamically, just ask for a file:
Console.WriteLine("Enter a file to search");
String fileName = Console.ReadLine().Trim();
if (File.Exists(fileName)) {
Console.WriteLine("Enter a word to search");
String pattern = Console.ReadLine().Trim();
// Do not forget to escape the pattern!
int count = Regex.Matches(File.ReadAllText(fileName),
Regex.Escape(pattern),
RegexOptions.IgnoreCase).Count;
Console.WriteLine(count.ToString());
}
Console.ReadLine();
}
答案 3 :(得分:0)
string cCriteria = @"\b" + cSearforSomething + @"\b";
这是你的问题。如果从每一端删除@“\ b”,您将获得正确数量的“#”字符,因为这些字符表示单词的结尾,而“#”字符不是它自己的单词。