计算字符串C#中的连续数字

时间:2015-02-19 08:00:20

标签: c#

我有一个字符串{101110111010001111}我正在搜索所有相等位序列的总数,其精确长度为3位。在上面的字符串中,答案将是3(请注意,最后一个“1111”不计算,因为它有超过3个相等的位。 有什么建议怎么做?

6 个答案:

答案 0 :(得分:5)

如果您不想要一个简单的解决方案,请尝试以下方法:

string s = "1101110111010001111";
var regex = new Regex(@"(.)\1+");
var matches = regex.Matches(s);
int count = matches.Cast<Match>().Where(x => x.Length == 3).Count();

说明:

  • 正则表达式找到2个或更多相同字符的集合(不限于0&#39; s和1&#39;)
  • 然后只计算正好3个字符的集合

答案 1 :(得分:1)

你需要吗?有时最简单的解决方案是最好的:

public static int Count(string txt)
{
    // TODO validation etc
    var result = 0;
    char lstChr = txt[0];
    int lastChrCnt = 1;

    for (var i = 1; i < txt.Length; i++)
    {
        if (txt[i] == lstChr)
        {
            lastChrCnt += 1;
        }
        else
        {
            if (lastChrCnt == 3)
            {
                result += 1;
            }

            lstChr = txt[i];
            lastChrCnt = 1;
        }
    }

    return lastChrCnt == 3 ? result + 1 : result;
}

答案 2 :(得分:1)

您可以使用正则表达式:

Regex.Matches(s, @"((?<=0)|^)111((?=0)|$)|((?<=1)|^)000((?=1)|$)");

这里的评论表达方式相同:

Regex.Matches(s, @"
    (
        (?<=0)           # is preceeded by a 0
        |                # or
        ^                # is at start
    )
    111                  # 3 1's
    (
        (?=0)            # is followed by a 0
        |                # or
        $                # is at start
    )
    |                    # - or -
    (
        (?<=1)           # is preceeded by a 1
        |                # or
        ^                # is at start
    )
    000                  # 3 0's
    (
        (?=1)            # followed by a 1
        |                # or
        $                # is at end
    )", RegexOptions.IgnorePatternWhitespace).Dump();

答案 3 :(得分:0)

您可以将字符串拆分为“111”以获取数组。然后,您可以使用linq简单地计算不以“1”开头的行。

参见示例:

using System;
using System.Linq;

namespace experiment
{
    class Program
    {
        static void Main(string[] args)
        {
            string data = "{101110111010001111}";
            string[] sequences = data.Split(new string[] {"111"}, StringSplitOptions.None);
            int validCounts = sequences.Count(i => i.Substring(0, 1) != "1");
            Console.WriteLine("Count of sequences: {0}", validCounts);
            // See the splited array
            foreach (string item in sequences) {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
    }
}

答案 4 :(得分:0)

另一种方法:由于你只计算位数,你可以将字符串拆分为“1”和“0”,然后用长度3计算所有元素:

string inputstring = "101110111010001111";
string[] str1 = inputstring.Split('0');
string[] str2 = inputstring.Split('1');
int result = str1.Where(s => s.Length == 3).Count() + str2.Where(s => s.Length == 3).Count();
return result

答案 5 :(得分:0)

算法解决方案。检查任意n个连续字符。但是并没有对所有负面情况进行全面测试。

public static int GetConsecutiveCharacterCount(this string input, int n)
{
   // Does not contain expected number of characters
   if (input.Length < n || n < 1)
      return 0;

   return Enumerable.Range(0, input.Length - (n - 1)) // Last n-1 characters will be covered in the last but one iteration.
                    .Where(x => Enumerable.Range(x, n).All(y => input[x] == input[y]) && // Check whether n consecutive characters match
                                ((x - 1) > -1 ? input[x] != input[x - 1] : true) && // Compare the previous character where applicable
                                ((x + n) < input.Length ? input[x] != input[x + n] : true) // Compare the next character where applicable
                     )
                    .Count();
}