我需要功能方面的帮助

时间:2019-06-26 12:52:09

标签: c# project

所以我一直在努力用C#编写函数 接收单词的字符串数组(这些函数在被函数接收之前先从字符串拆分为单词数组)。

所以我一直想做的一个功能是检查整个数组中是否有{> {3}以外的单词(单词是单词数组的名称)之外的字母是否显示超过3个次(最少3次)。

例如,这句话:

  

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

因为一个单词中字母的存在不超过3次-像这样的单词不存在。 函数的基础如下:

words[0]

到目前为止,我想出了什么...我知道有错误...我还没有解决:

public bool MultipleCheck(string[] words)
{

}

2 个答案:

答案 0 :(得分:1)

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

public static class StringExt {
    public static bool WordHasConsecutive(this string word, int n) {
        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));

答案 1 :(得分:0)

我希望这会起作用

private static Tuple<bool, string> ValidateWord(string[] words)
{
    bool foundResult = false;
    List<string> all3CharWords = new List<string>();
    string wordWith3SameChar = string.Empty;

    foreach (var word in words)
    {
        var resultTuple = ValidateWord(word);
        if (resultTuple.Item1)
        {
            foundResult = true;
            all3CharWords.Add(resultTuple.Item2);
        }
    }

    if (foundResult)
    {
        wordWith3SameChar = String.Join(";", all3CharWords.ToArray());
    }

    return new Tuple<bool, string>(foundResult, wordWith3SameChar);
}


private static Tuple<bool, string> ValidateWord(string words)
{
    bool foundResult = false;
    string wordWith3SameChar = string.Empty;
    List<string> traversedChars = new List<string>();
    for(int i = 0; i < words.Length; i++)
    {
        if (!traversedChars.Contains(words[i].ToString()))
        {
            string tripleChar = $"{words[i]}{words[i]}{words[i]}";
            if (words.Contains(tripleChar))
            {
                foundResult = true;
                wordWith3SameChar = words;
                break;
            }
        }
    }

    return new Tuple<bool, string>(foundResult, wordWith3SameChar);
}

通过以下呼叫,您将得到答案

var resultTuple = ValidateWord("Why llll ddd ssssssss".Split(' ').ToArray());
if (resultTuple.Item1)
{
    Console.WriteLine($"The following words have 3 similar charecters: " + resultTuple.Item2);
}
else
{
    Console.WriteLine("No words has consecutive 3 similar charecters.");
}