C#如何计算我在txt文件中写的字数 [英] C# how to count the number of words I wrote in txt file

查看:97
本文介绍了C#如何计算我在txt文件中写的字数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在txt文件中我有一句话:请写任何句子

i必须创建具有2个参数`第一个文件的函数地址,第二个是任何单词

此函数必须返回遇到单词的次数在句子中。

例如,如果我将在主要这样称呼它`

in txt file i have a sentence: Please write any Sentence.
i must create function which has 2 parameter` first file address,the second is any word.
This function must return how many times did encounter the word in the sentence.
For example if i will call it in main like this`

Console.WriteLine(Counter(hasce,"any"));



它将打印1,因为句子中有1个单词名称 any



我尝试过的事情:



我试过这样的事情。


it will print 1, because there is 1 word name of "any" in sentence.

What I have tried:

I've tried like this`

static public int Counter(string address,string word)
        {
            int myword= 0;
            string text = File.ReadAllText(address);
            if (word == text)
            {
                myword++;
            }
            
            return myword;
        }







static void Main(string[] args)
        {
           Console.WriteLine(Counter(address,"any"));
        }

推荐答案

请阅读我对此问题的评论。



您必须拆分 [ ^ ]空格上的字符串,例如:

PLease, read my comment to the question.

You have to Split[^] string on spaces, for example:
string address = "Please write any Sentence";
string filter = "any";

int counter = address.Split(new string[]{" "}, StringSplitOptions.RemoveEmptyEntries).Count(x=>x==filter);
Console.WriteLine("{0}", counter);







我忘了提及上/下字母!请注意比较:(any==Any)返回 false

我强烈建议您阅读:

如何:比较字符串(C#编程指南)| Microsoft Docs [ ^ ]

String.Compare方法(字符串,字符串,布尔值)(系统) [ ^ ]



祝你好运!

< br $>




由于OP的评论,这是一个完整的例子:




I forgot to mention about upper/lower letters! Note that comparison: ("any"=="Any") returns false.
I'd strongly recommend to read this:
How to: Compare strings (C# Programming Guide) | Microsoft Docs[^]
String.Compare Method (String, String, Boolean) (System)[^]

Good luck!



Due to OP's comments, here is a complete example:

void Main()
{
	
	string path = @"D:\data.txt";
	string find = "any";
	string[] lines =  File.ReadAllLines(path);
	int cTotal = 0;
	
	foreach(string line in lines)
	{
		cTotal += Counter(line, find);
	}
	
	Console.WriteLine("A '{0}' has been found {1} time", find, cTotal);
	
}

// Define other methods and classes here
public static int Counter(string line, string findword)
{
	int c= 0;
	
	string[] words = line.Split(new string[]{" "}, StringSplitOptions.RemoveEmptyEntries);
	foreach(string word in words)
	{
		if (string.Compare(word, findword, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.CompareOptions.IgnoreCase)==0)
		{
			c++;
		}
	}
	return c
}





更多:

File.ReadAllLines Method(String)(System.IO) [ ^ ]


这篇关于C#如何计算我在txt文件中写的字数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆