查找在给定字符串C#中将生成的组数量#

查找在给定字符串C#中将生成的组数量#

本文介绍了查找在给定字符串C#中将生成的组数量#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

离。假设我输入为:

ex. suppose i give input as:

ABCDE => result is:1 
ABACDAE => result:1
ABCDEABCDE => 2.. etc.





我的尝试:





What I have tried:

static void Main(string[] args)
        {
            string patern = "ABCDE";
            Console.WriteLine("enter input");
            string input = Console.ReadLine();
            int count = 0;
            string str = "";
            for (int i = 0; i < input.Length; i++)
            {
                str = str + input[i];
                if (str == patern)
                {
                    count++;
                    str = "";
                }
            }
            Console.WriteLine("count:" + count);
        }

推荐答案

public static void Main(string[] args)
        {
            string patern = "ABCDE";
            Console.WriteLine("enter input");
            string input = "ABCDEABCDE";
            int count = 0;
            for (int i = 0; i < input.Length - 4; i++)
            {
                //take first 5 letters 
                string first5Letters = input.Substring(i, 5).ToUpper();
                if (first5Letters.Contains(patern))
                {
                    count++;
                }


            }
            Console.WriteLine(count);
        }


这篇关于查找在给定字符串C#中将生成的组数量#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 03:09