[英]How do I change this code to get the longest continuous sequence of Cs rather than the longest continuous sequence of any character
我做了一个解决方案,它给了我最长连续字符序列的值,但是我需要如何修改它以指定我需要字符 C 的最长连续序列? 或者我会完全需要一个全新的代码块吗?
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;
}
}
}
如果您发现char
不是您搜索的那个,则必须continue
外循环:
public int Longest(string mySequence, char c = '\0')
{
// ...
for (int i = 0; i < length; i++)
if (c != '\0' && mySequence[i]!= c)
continue;
// ...
演示: https://dotnetfiddle.net/5pYxbJ
请注意,您不需要用string
中的字符填充char[]
。 您可以将任何字符串视为char[]
。 只需使用索引器。 如果您真的需要char[]
,请使用ToCharArray
。 我在演示中更改了您的代码以显示我的意思。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.