我该如何解决这个C#问题 [英] How do I solve this C# problem

查看:68
本文介绍了我该如何解决这个C#问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个包含句子的输入文本文件。



每个句子都用。,!,?分隔。

每个句子都包含由一个或多个分隔的单词。



应编写程序,阅读文本文件,查找句子,对它们进行排序并将它们写回输出文件。



输出文件应该是每行一个句子。



排序的标准是:

1)如果句子包含更多相等的单词,则句子大于其他句子

2)句子更大,如果包含更多单词

3)如果包含更多字符,则句子更大



标准应按1,2,3的顺序应用


示例输入文件:



Hello World。你好你好美丽的世界!世界上有更多的单词比单词中的世界更多。这是

一句话。我的名字是Neo。



预期输出文件:



您好,你好美丽的世界!

世界上的单词比世界上的单词更多。

这是一个句子。

我的名字是Neo。

Hello World。



我写了检查单词数,字母数和重复的话。我不知道如何迭代句子并对它们进行排序



  class  CountWords 
{
static void Main(< span class =code-keyword> string [] args)
{

string text = File。 ReadAllText( ../../ words.txt);

string [] sentences = Regex.Split(text, @ < span class =code-string>(?< = [\。!\?])\ s);

var wordsCount = new INT [sentences.Length];

for int i = 0 ; i < sentences.Length; i ++)
{
var 最大=句子[ 0 ];

}



}
public int [] WorldCounter( string []句子)
{
var wordsCount = new int [sentences.Length];

for int i = 0 ; i < sentences.Length; i ++)
{
wordsCount [i] =句子[i]
.Split( new [] { },StringSplitOptions.RemoveEmptyEntries)
.Count();
}

return wordsCount;
}

public int [] LetterCounter( string []句子)
{
return 句子
。选择(c = > c.Length)
.ToArray();
}

public int [] DublicatesCounter( string []句子)
{
int [] dublicates = new int [sentences.Length];

for int i = 0 ; i < sentences.Length; i ++)
{
var splited = sentences [i] .Split( new [] { },StringSplitOptions.RemoveEmptyEntries);

bool [] isChecked = new BOOL [splited.Length];

for int j = 0 ; j < splited.Length - 1 ; j ++)
{
var currentWord = splited [j];

for int k = j + 1 ; k < splited.Length; k ++)
{
if (isChecked [k])
{
continue ;
}

如果(currentWord == splited [k])
{
dublicates [i] ++;
isChecked [k] = true ;
}
}
}
}

return dublicates;
}
}

解决方案

嗨!



首先,似乎预期的输出不是尊重你的规则的输出。



世界上的单词比单词中的世界更多应该是第一个,因为它包含两个重复: in 的。



现在的预期输出是:

世界上的单词比世界上的单词更多。

您好,你好美丽的世界!

这句话。

我的名字是Neo。

Hello World。



以下是我的建议:



创建课程怎么样?使用自定义 Sort()方法。

由于此类已被密封,因此无法覆盖String类的 Sort()方法。



所以我们创建一个类只是为了封装你的 String 并创建你自己的 Sort()方法。

让我们调用这个类 CustomString



为了能够使用 Sort()方法,你必须实现 IComparable 界面。为了实现这个接口,你所要做的就是创建方法 CompareTo ()。



CompareTo 表示应如何比较两个元素。好的一点是你知道你的比较元素:

- 重复的单词

- 单词数

- 字符数



请参阅此处如何实现接口:



使用.NET中的IComparable和IComparer接口对列表进行排序



之后,您只需在 CustomString 列表中使用 Sort()





既然你似乎有点挣扎并且害怕我的解决方案,我必须告诉你它有多简单。



80%的代码是你的。



解决方案:



 < span class =code-keyword>使用 System.IO; 
使用 System.Linq;
使用 System.Text.RegularExpressions;

命名空间 CustomCompare
{
internal class 程序
{
private static void Main( string [] args)
{
// 您的代码
var text = File.ReadAllText( 您的文件);

var sentences = Regex.Split(text, @ (小于?= [\!?])\s);

// 将包含已排序的元素
var sortedList = sentences.Select(sentence = > new CustomString(句子))。ToList();

// 简单排序调用
sortedList.Sort() ;

// 显示
foreach var customString in sortedList)
{
Console.WriteLine(customString.CustString);
}
// 等待能够读取输出
Console.Read();
}
}

内部 CustomString: IComparable的< CustomString>
{
// 简单构造函数
public CustomString( string custString)
{
CustString = custString;
}

// 封装字符串
public string CustString { get ; set ; }
// 比较的实现。
public int CompareTo(CustomString other)
{
// 我们比较重复单词的数量
var thisNumberOfDuplicate = DublicatesCounter(CustString);
var otherNumberOfDuplicate = DublicatesCounter(other.CustString);

if (thisNumberOfDuplicate > otherNumberOfDuplicate)
返回 -1;
if (thisNumberOfDuplicate < otherNumberOfDuplicate)
返回 1 ;

// 我们比较单词数
var thisNumberOfWords = WordCounter(CustString);
var otherNumberOfWords = WordCounter(other.CustString);

if (thisNumberOfWords > otherNumberOfWords)
返回 -1;
if (thisNumberOfWords > otherNumberOfWords)
返回 1 ;

// 我们比较一个或多个字符
var thisNumberOfCharacter = LetterCounter(CustString);
var otherNumberOfCharacter = LetterCounter(other.CustString);

if (thisNumberOfCharacter > otherNumberOfCharacter)
返回 -1;
if (thisNumberOfCharacter < otherNumberOfCharacter)
返回 1 ;
return 0 ;
}

// 您的代码没有数组
private int WordCounter( string 句子)
{
var wordsCount = 0 ;
wordsCount =句子
.Split( new [] { },StringSplitOptions.RemoveEmptyEntries)
.Count();
return wordsCount;
}

// 您的代码没有数组
private int LetterCounter( string 句子)
{
return sentence.Length;
}

// 您的代码没有数组
// 已修改,因为Hello!= hello
// 您的预期输出需要Hello = hello
// < span class =code-comment>所以你需要添加.toLower()

private int DublicatesCounter( string 句子)
{
var numberOfDuplicate = 0 ;

var splited = sentence.Split( new [] { },StringSplitOptions.RemoveEmptyEntries);
var isChecked = new bool [splited.Length];

for var j = 0 ; j < splited.Length - 1 ; j ++)
{
var currentWord = splited [j];

for var k = j + 1 ; k < splited.Length; k ++)
{
if (isChecked [k])
{
continue ;
}

if (currentWord.ToLower()== splited [k] .ToLower())
{
numberOfDuplicate ++;
isChecked [k] = true ;
}
}
}
return numberOfDuplicate;
}
}
}





输出:



世界上的单词比单词中的世界更多。 
你好你好美丽的世界!
这是一个句子。
我的名字是Neo。
Hello World。


首先看问题:排序算法有三个阶段:

1)相等单词

然后

2)字数

最后

3)字符数。

最后两个非常简单。

第一个也不难。

首先获取包含单词的字符串数组并对它们进行排序:

 Array.Sort(单词); 

将会这样做。

现在,相同的单词彼此相邻,并且很容易在循环中发现:

  int  copies =  0 ; 
string lastWord = null ;
foreach 字符串 单词)
{
if (word == lastWord)copy ++;
lastWord = word;
}


对于自学,以下书籍非常有用:。由Charles Petzold撰​​写的.NET Book Zero [ ^ ]。

We have an input text file, containing sentences.

Each sentence is delimited by ".", "!", "?"
Each sentence contains words, delimited by one or more " ".

A program should be written, to read the text file, to find the sentences, to sort them and to write them back to output file.

The output file should be one sentence per line.

The criteria for sorting are:
1) A sentence is bigger than other if it contains more equal words
2) A sentence is bigger, if contains more words
3) A sentence is bigger, if contains more characters

The criteria should be applied in order 1, 2, 3

Example input file:

Hello World. Hello hello beautiful world! There are
more words in the world than worlds in the word. This is
a sentence. My name is Neo.

Expected output file:

Hello hello beautiful world!
There are more words in the world than worlds in the word.
This is a sentence.
My name is Neo.
Hello World.

I wrote the methods for checking for words count, letters count and repeating words. I don't get how to iterate through the sentences and sort them

class CountWords
{
    static void Main(string[] args)
    {

        string text = File.ReadAllText("../../words.txt");

        string[] sentences = Regex.Split(text, @"(?<=[\.!\?])\s");
        
        var wordsCount = new int[sentences.Length];

        for (int i = 0; i < sentences.Length; i++)
        {
            var biggest = sentences[0];

        }


       
    }
    public int[] WorldCounter(string[] sentences)
    {
        var wordsCount = new int[sentences.Length];

        for (int i = 0; i < sentences.Length; i++)
        {
            wordsCount[i] = sentences[i]
                                .Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                                .Count();
        }

        return wordsCount;
    }

    public int[] LetterCounter(string[] sentences)
    {
        return sentences
                .Select(c => c.Length)
                .ToArray();
    }

    public int[] DublicatesCounter(string[] sentences)
    {
        int[] dublicates = new int[sentences.Length];

        for (int i = 0; i < sentences.Length; i++)
        {
            var splited = sentences[i].Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);

            bool[] isChecked = new bool[splited.Length];

            for (int j = 0; j < splited.Length - 1; j++)
            {
                var currentWord = splited[j];

                for (int k = j + 1; k < splited.Length; k++)
                {
                    if (isChecked[k])
                    {
                        continue;
                    }

                    if (currentWord == splited[k])
                    {
                        dublicates[i]++;
                        isChecked[k] = true;
                    }
                }
            }
        }

        return dublicates;
    }
}

解决方案

Hi !

First it seems that the expected output is not the one which respects your rules.

"There are more words in the world than worlds in the word" should be first since it contains two duplicates : "in" and "the".

The expected output is now :
There are more words in the world than worlds in the word.
Hello hello beautiful world!
This is a sentence.
My name is Neo.
Hello World.

After here is my suggestion :

What about creating a class with a custom Sort() method.
It's not possible to override Sort() method of the String class since this class is sealed.

So we create a class only to encapsulate your String and create your own Sort() method.
Lets call this class CustomString.

In order to be able to use the Sort() method, you have to implement the IComparable interface. In order to implement this interface, all you have to do is to create the method CompareTo().

CompareTo indicates how two elements should be compared. The good point is that you know your comparison elements :
- Duplicate words
- Number of words
- Number of characters

See here how to implement the inteface :

Sorting Lists using IComparable and IComparer Interface in .NET

And after, you just have to use Sort() on your List of CustomString.


Since you seems to struggle a bit and be afraid by my solution, i must show you how simple it is.

80% of the code is your.

Solution :

using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace CustomCompare
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //Your code
            var text = File.ReadAllText("Your File");

            var sentences = Regex.Split(text, @"(?<=[\.!\?])\s");

            //Will contain the sorted elements 
            var sortedList = sentences.Select(sentence => new CustomString(sentence)).ToList();

            //Simple Sort call 
            sortedList.Sort();

            //Display
            foreach (var customString in sortedList)
            {
                Console.WriteLine(customString.CustString);
            }
            //Wait to be able to read output
            Console.Read();
        }
    }

    internal class CustomString : IComparable<CustomString>
    {
        //Simple constructor
        public CustomString(string custString)
        {
            CustString = custString;
        }

        //The encapsulated string 
        public string CustString { get; set; }
        //The implementation of compare to. 
        public int CompareTo(CustomString other)
        {
            //We compare the number of duplicated words
            var thisNumberOfDuplicate = DublicatesCounter(CustString);
            var otherNumberOfDuplicate = DublicatesCounter(other.CustString);

            if (thisNumberOfDuplicate > otherNumberOfDuplicate)
                return -1;
            if (thisNumberOfDuplicate < otherNumberOfDuplicate)
                return 1;

            //We compare the number of words
            var thisNumberOfWords = WordCounter(CustString);
            var otherNumberOfWords = WordCounter(other.CustString);

            if (thisNumberOfWords > otherNumberOfWords)
                return -1;
            if (thisNumberOfWords > otherNumberOfWords)
                return 1;

            //We compare the number or characters
            var thisNumberOfCharacter = LetterCounter(CustString);
            var otherNumberOfCharacter = LetterCounter(other.CustString);

            if (thisNumberOfCharacter > otherNumberOfCharacter)
                return -1;
            if (thisNumberOfCharacter < otherNumberOfCharacter)
                return 1;
            return 0;
        }

        //Your code without array
        private int WordCounter(string sentence)
        {
            var wordsCount = 0;
            wordsCount = sentence
                .Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries)
                .Count();
            return wordsCount;
        }

        //Your code without array 
        private int LetterCounter(string sentence)
        {
            return sentence.Length;
        }

        //Your code without array 
        //Modified because Hello != hello
        //Your expected output expects that Hello = hello
        //So you need to add .toLower()
        private int DublicatesCounter(string sentence)
        {
            var numberOfDuplicate = 0;

            var splited = sentence.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries);
            var isChecked = new bool[splited.Length];

            for (var j = 0; j < splited.Length - 1; j++)
            {
                var currentWord = splited[j];

                for (var k = j + 1; k < splited.Length; k++)
                {
                    if (isChecked[k])
                    {
                        continue;
                    }

                    if (currentWord.ToLower() == splited[k].ToLower())
                    {
                        numberOfDuplicate++;
                        isChecked[k] = true;
                    }
                }
            }
            return numberOfDuplicate;
        }
    }
}



Output:

There are more words in the world than worlds in the word.
Hello hello beautiful world!
This is a sentence.
My name is Neo.
Hello World.


Start by looking at the problem: the sort algorithm has three phases:
1) equal words
Then
2) Word count
Finally
3) Character count.
The last two are pretty trivial.
The first isn't difficult either.
Start by taking the string arrays that contain the words and sort them:

Array.Sort(words);

will do it.
Now, identical words are next to each other, and very easy to spot in a loop:

int copies = 0;
string lastWord = null;
foreach (string word in words)
    {
    if (word == lastWord) copies++;
    lastWord = word;
    }


For self-education, the following book is very useful: .NET Book Zero by Charles Petzold[^].


这篇关于我该如何解决这个C#问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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