Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 计算字符串中的唯一单词_C# - Fatal编程技术网

C# 计算字符串中的唯一单词

C# 计算字符串中的唯一单词,c#,C#,我有一个页面叫做post summary。 在这个页面下,我想计算单词总数和唯一单词总数。 我成功地算出了帖子的总字数。 然而,我不知道如何计算这些独特的单词 我今天很喜欢上学 预期产出: Total word count: 6 Unique word count: 5 这是我目前的代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using S

我有一个页面叫做post summary。 在这个页面下,我想计算单词总数和唯一单词总数。 我成功地算出了帖子的总字数。 然而,我不知道如何计算这些独特的单词

我今天很喜欢上学

预期产出:

Total word count: 6
Unique word count: 5
这是我目前的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace empTRUST
{
    public partial class PostSummary : Form
    {
        string target_fbid;
        string fbStatus;

        public PostSummary(string target_fbid, string fbStatus)
        {
            InitializeComponent();
            this.target_fbid = target_fbid;
            this.fbStatus = fbStatus;
        }

        private void PostSummary_Load(object sender, EventArgs e)
        {
            label_totalwordcount.Text = fbStatus.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
        }
    }
}

您可以使用以下内容:

"I enjoyed school school today very much.".Split(' ').Distinct()
这一个返回6,即使有学校单词出现2次

编辑


如果你需要一些自定义的比较逻辑,比如说不区分大小写,你可以在你可以指定自定义相等比较器的地方使用。

我不理解你的例子,因为在我今天非常喜欢的学校里没有重复的单词。但是,这是一种幼稚的方法,可能适合您:

var allWords = text.Split();
int count = allWords.Length;  // 6
int unqiueCount = allWords.Distinct().Count();  // 6
这很幼稚,因为标点符号会修改结果。因此,您可能希望在第一步中替换它们:

var allWords = text.ToUpperInvariant().Replace(".", "").Replace(",","").Split(); // ...
此外,案例会修改结果,因此如果需要,您可以不敏感地比较案例

第一个问题是:

public int GetUniqueWordsCount(string input)
{
    return input.Split(' ').GroupBy(s => s).Count();
}

如果您想要不区分大小写的解决方案,可以将.ToLower或.ToUpper转换添加到组键选择器中。如果您需要自定义比较逻辑,您也可以实现自己的iQualityComparer。

您是如何从我今天非常喜欢的学校获得5的唯一字数的?我想他指的是唯一的letters@Sam如果他指的是字母,那就不止5个了。请解释一下你对“单词”的定义。请检查一下你的样本。但是会返回3,否?@ta.speot.is:我编辑了我的答案。我认为这里可以使用Char.isleter和Char.IsWhitespace函数。@ta.speot.is:问题是我们不知道字符串的格式。