使用C#计数的话每句 [英] Counting words in each sentence using C#

查看:98
本文介绍了使用C#计数的话每句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个程序,它显示了它字数最多的一句话。

I need to create a program that shows a sentence with the most words in it.

string [] st = { "I like apples.", 
                 "I like red apples.", 
                 "I like red apples than green apples." 
};

foreach (string s in st)
{
    int NumberOfWords = s.Split(' ').Length;
}



结果应该显示我喜欢红苹果比青苹果。

The result should be displaying "I like red apples than green apples".

推荐答案

也许,你在不同的文本框控制句子的形式。因为你知道哪些句子含有更多的字;通过空间分割句子,并得到单词的数量,然后就可以进行比较。类似下面。

Probably, you have the sentences in different TextBox control in your Form. For you to know which sentence have more words in it; split the sentence by space and get a count of words and then you can compare. something like below.

int str1 = "I like apples".Split(' ').Length;
int str2 = "I like red apples".Split(' ').Length;
int str3 = "I like red apples than green apples".Split(' ').Length;

下面拆分()函数返回一个字符串数组,这样你可以得到长度它。现在你可以很容易地对它们进行比较

Here split() functions returns a string array and so you can get Length of it. Now you can compare them easily.

编辑:

下面将是一个完整的示例代码绘制在您发布的代码。存储在 INT [] 数组的字数。然后对数组进行排序。很显然,在改编下面的最后一个元素将是具有最高的词之一。

Below would be a full example code drawn over your posted code. Store the word count in a int[] array. Then sort the array. Obviously the last element in arr below would be the one having highest words.

    static void Main(string[] args)
    {
        int[] arr = new int[3];           
        string[] st = { "I like apples.", "I like red apples.", 
                             "I like red apples than green apples." };
        int counter = 0;
        foreach (string s in st)
        {
            int NumberOfWords = s.Split(' ').Length;
            arr[counter] = NumberOfWords;
            counter++;
        }

        Array.Sort(arr);

        Console.WriteLine(st[arr.Length - 1]);
    }

这篇关于使用C#计数的话每句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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