C#方法/函数,如果字符重复出现在字符串中,则返回true或false

时间:2016-06-26 16:11:08

标签: c#

我需要使用C#编写一个方法/函数,它接受两个参数:一个字符串和一个字符。如果对于字符串中的每个字符实例,该函数应该返回true,该字符的另一个实例立即向左或向右。换句话说,只有当字符仅作为一对出现在字符串中时,该函数才会返回true。我似乎无法弄明白。

示例:

Manipulation("abcdeefghi", 'e') -> true
Manipulation("abcdeeefghi", 'e') -> false

目前我有:

public bool Manipulation(string strParam, char[] charParam)
{
    if (strParam.Contains(charParam))
    {
        return true;                
    }
    return false;
}

我已经知道这不起作用,但如果我能在字符串中找到至少一次,我至少会尝试返回true。

3 个答案:

答案 0 :(得分:1)

一种看待它的方法是遍历字符串一次,只检查你的字符是否出现:请注意,这个答案要求char出现两次,例如:

IsPairOccurence("abcdeefghi", 'e') -> true
IsPairOccurence("abcdeeefghi", 'e') -> false

检查至少两次是否更容易,如@ aditya的答案所示。

private bool IsPairOccurence(string s, char c) {
    int occurence = 0; // the number of consecutive occurences
    for (int i = 0; i < s.Length; i++) {
        if (s[i] == c) { // If you encounter the character
            occurrence++; // Increase the counter
        } else { // If another character occurs
            if (occurence == 2) {
            // Check if the number of consecutive occurences was exactly 2
                return true;
            }
            // If not, reset the counter
            occurence = 0;
        }
    }
    return occurence == 2;
}

对于任何情况,这个答案都很容易概括,例如:如果你想计算连续3个或24个连续字符的出现次数。您甚至可以将其概括为n个连续字符:

private bool DoesOccurNTimes(string s, char c, int n) {
    int occurence = 0; // the number of consecutive occurences
    for (int i = 0; i < s.Length; i++) {
        if (s[i] == c) { // If you encounter the character
            occurrence++; // Increase the counter
        } else { // If another character occurs
            if (occurence == n) {
            // Check if the number of consecutive occurences was exactly n
                return true;
            }
            // If not, reset the counter
            occurence = 0;
        }
    }
    // Check for the end of the string
    return occurence == n;
}

现在IsPairOccurence(s, c)只是DoesOccurNTimes(s, c, 2)

答案 1 :(得分:0)

这应该对你有用,但正如@ThreeFx在评论中建议的那样,你需要提一下它是否仅适用于对或三元组等等。

然而,答案假设后一种情况:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StackQuestionAnswersCS
{
    class Program
    {
        static void Main(string[] args)
        {
            if (checkContains("HelloWorld", 'o')) Console.WriteLine("Contains Character");
            else Console.WriteLine("Does not contain character");
            Console.ReadLine();
        }

        static bool checkContains(string input, char character)
        {
            for (int i = 0; i < input.Length - 1; i++)
            {
                if (input[i] == character && input[i+1] == character) return true;
            }
            return false;
        }
    }
}

答案 2 :(得分:0)

private static bool Manipulation(string p, char c)
{
   return p.Contains(c.ToString() + c.ToString()) && !p.Replace(c.ToString() + c.ToString(), "").Contains(c);
}
相关问题