How do I change this code to get the longest continuous sequence of Cs rather than the longest continuous sequence of any character

Viewed 40

I made a solution that gave me the value of the longest continuous sequence of characters, but how would I need to modify it to specify I need the longest continuous sequence of the character C? Or would I need a whole new block of code completely?

using System;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography;
using System.Text;

namespace CarCounting
{
    internal class Program
    {
        static void Main(string[] args)
        {
            CarCounting newSequence = new CarCounting();   
            Console.WriteLine(newSequence.longest("CCMCCCCLLCCC")); //executes the function
  
        }
    }

    public class CarCounting
    {

        public CarCounting()
        {

        }


        public int longest(string mySequence)
        {
            //turns the argument into an array
            char[] charC = new char[mySequence.Length]; 
            for (int i = 0; i < mySequence.Length; i++) 
            {
                charC[i] = mySequence[i];
            }

            int charCcount = 0;
            int length = charC.Length;
            
            //compares the values in the array
            for(int i = 0; i < length; i++)  
            {
                int currentcount = 1;
                for (int j = i + 1; j < length; j++) 
                {
                    if (charC[i] != charC[j]) 
                        break;
                    currentcount++;
                }
                if (currentcount > charCcount)
                {
                    charCcount = currentcount;
                }
            }


            return charCcount;

        }

    }

}
1 Answers

You have to continue the outer loop if you see that the char is not the one you search:

public int Longest(string mySequence, char c = '\0')
{
    // ...
    for (int i = 0; i < length; i++)
        if (c != '\0' && mySequence[i]!= c) 
            continue;
        // ...

Demo: https://dotnetfiddle.net/5pYxbJ

Note that you don't need to fill the char[] with the characters in the string. You can treat any string as it was a char[]. Just use the indexer. If you really need a char[], use ToCharArray. I have changed your code in my demo to show what i mean.

Related