gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
Write C# code to calculate leading character count and ending character count
- User
Write C# code to calculate leading character count and ending character count
- Assistant
Write C# code to calculate leading character count and ending character count
Certainly! Below is a C# program that calculates the leading character count and the ending character count for a given string. We will define leading character count as the number of times the first character appears consecutively from the start, and ending character count as the number of times the last character appears consecutively from the end.
using System;
class Program
{
static void Main()
{
// Example input
string input = "aaabbbcccddd";
int leadingCount = GetLeadingCharacterCount(input);
int endingCount = GetEndingCharacterCount(input);
Console.WriteLine($"Leading character count: {leadingCount}");
Console.WriteLine($"Ending character count: {endingCount}");
}
static int GetLeadingCharacterCount(string input)
{
if (string.IsNullOrEmpty(input))
return 0;
char leadingChar = input[0];
int count = 0;
foreach (char c in input)
{
if (c == leadingChar)
count++;
else
break;
}
return count;
}
static int GetEndingCharacterCount(string input)
{
if (string.IsNullOrEmpty(input))
return 0;
char endingChar = input[input.Length - 1];
int count = 0;
for (int i = input.Length - 1; i >= 0; i--)
{
if (input[i] == endingChar)
count++;
else
break;
}
return count;
}
}
GetLeadingCharacterCount Method:
input as a parameter.leadingChar.leadingChar appears consecutively.GetEndingCharacterCount Method:
input as a parameter.endingChar.endingChar appears consecutively from the end."aaabbbcccddd":
3 as 'a' appears three times consecutively.3 as 'd' appears three times consecutively.Not yet included in a published release.