首页 > 解决方案 > 我需要有关功能的帮助

问题描述

因此,我一直在努力在 C# 中编写一个函数,该函数接收一个字符串数组(在函数从字符串接收到单词数组之前被拆分)。

所以我一直在尝试做的是一个函数,它检查words[0]整个数组中是否有一个字母显示超过 3 次(最少 3 次)。

例如,这句话:

为什么 llll ddd ssssssss !!!!!!!?

因为没有一个字母在一个单词中出现超过 3 次——这样的单词是不存在的。函数的基础如下所示:

public bool MultipleCheck(string[] words)
{

}

到目前为止我想出了什么......我知道它有错误......我还没有修复它:

public bool AttachmentsCheck(string[] words)
{

    string currentWord;
    int wordCounter = 0;

    for (int i=0; i < words.Length; i++)
    {
        currentWord = words[i];
        for (int j = 0; j < currentWord.Length; j++)
        {
            char[] wordArr = currentWord.ToCharArray();
            for (int k=0; k < wordArr.Length; k++)
            {
                if (wordArr[k]==wordArr[wordArr.Length-k])
                {
                    wordCounter++;
                }
            }
        }
        if (wordCounter => 3)
        {
            return false;
        }
    }
    return true;
}

标签: c#project

解决方案


使用扩展方法确定一个单词是否有 n 个连续字符:

public static class StringExt {
    public static bool WordHasConsecutive(this string word, int n) {
        if (word.Length <= 1)
            return false;
        if (n < 2)
            return true;
        if (word.Length >= n) {
            var ch = word[0];
            var count = 1;
            for (int i = 1; i < word.Length; ++i) {
                if (word[i] == ch) {
                    if (++count == n)
                        return true;
                }
                else {
                    ch = word[i];
                    count = 1;
                }
            }
        }
        return false;
    }
}

答案很简单,只需返回运行长度至少为 3 的单词:

var ans = words.Where(w => w.WordHasConsecutive(3));

推荐阅读