> 其他 >
c#实现,统计一句英文句子中某个单词出现的次数.
人气:440 ℃ 时间:2020-05-19 18:57:15
解答
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string s,s1,s2;
int count = 0;
Console.WriteLine ("请输入你要查找的那个单词的句子:");
string str= Console.ReadLine ();
Console.WriteLine ("请输入你要查找的那个单词:");
string serchword= Console.ReadLine ();
int sbcount = serchword.Count();
for (int i = 0; i < str.Count(); i++)
{
if ( i == 0)
{
s1 = " ";
s2 = str.Substring(i + sbcount ,1);
s = str.Substring(i,sbcount);
if (s1 == " " && s2 == " ")
{
if (s == serchword)
count++;
}
}
if (i + serchword.Count() < str.Count() && i != 0)
{
s1 = str.Substring(i - 1,1);
s2 = str.Substring(i + sbcount-1 ,1);
s = str.Substring(i,sbcount);
if (s1 == " " && s2 == " ")
{
if (s == serchword)
count++;
}
}
if (i + serchword.Count() == str.Count() )
{
s1 = str.Substring(i - 1,1);
s2 = " ";
s = str.Substring(i,sbcount);
if (s1 == " " && s2 == " ")
{
if (s == serchword)
count++;
}
break;
}
}
Console.WriteLine(count );
Console.ReadLine();
}
}
}你把题目说具体些,要在哪个控件上显示数据上面是英文句子,而这里是字符串,到底是个英文句子(有空格的Look at the ball),还是随便写的,如 dfl j;thedfal; thesdjf 这里的the的个数哥们,不好意思,今天才看到,但是我发现你的还是有问题的,如果你输入的内容没有the,就会不对,如ddgga,改成如下: string str = textBox1.Text.ToLower();int m = 0;for (int i = 0; i < str.Length; i++){int n = str.IndexOf("the") + 3;if (str.IndexOf("the") == -1)break;if (n > i) m++;str = str.Substring(n);}label1.Text = "the 出现的次数=" + m;下面是我做的,你可以参考下: int indexnumber = 0;string str = textBox1.Text.ToLower();int count= 0;for (int i = 0; i < str.Length; i++){indexnumber = str.IndexOf("the",indexnumber );if (indexnumber == -1)break;indexnumber++;count++;}label1.Text = "the 出现的次数=" + count;
推荐
猜你喜欢
© 2024 79432.Com All Rights Reserved.
电脑版|手机版