Samuël Búrns Samuël Búrns - 13 days ago 8
C# Question

Returning an Int Array from a Custom String Method?

I am creating a custom method that returns

AnalyzerInts[]
to count lowercase, uppercase, whitespace, punctuation, and character count of
string input
. I am getting an unhandled exception error. "System.IndexOutOfRangeException: Index was outside the bounds of the array." How do I correctly retrieve my
Int[] AnalyzerInts
values into my main method?

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a string/sentence: ");
string userInput = Console.ReadLine();
int[] answers = StringAnalyzer(userInput);
Console.WriteLine("You have {0} uppercase letters in your string.", answers[0]);
Console.WriteLine("You have {0} lowercase letters in your string.", answers[1]);
Console.WriteLine("You have {0} whitespace characters in your string.", answers[2]);
Console.WriteLine("You have {0} punctuation characters in your string.", answers[3]);
Console.WriteLine("You have {0} characters in your string.", answers[4]);
}





static int[] StringAnalyzer (string input)
{
int[] AnalyzerInts = new int[4];
for (int x = 0; x < input.Length; x++)
{
if (char.IsUpper(input[x]))
{
AnalyzerInts[0]++;
}
else if (char.IsLower(input[x]))
{
AnalyzerInts[1]++;
}
else if (char.IsWhiteSpace(input[x]))
{
AnalyzerInts[2]++;
}
else if (char.IsPunctuation(input[x]))
{
AnalyzerInts[3]++;
}
AnalyzerInts[4]++;
}
return AnalyzerInts;
}

Answer

A method definition can be viewed as [return type] [method name] ([parameters]) In your case, you defined StringAnalyzer to receive a string parameter named input and return a string value (that's indicated by string before the method name)

What you're looking for is to have the method accept a string but return an array of integers int[], so the method should be defined as

static int[] StringAnalyzer(string input) { /*...*/}

Also, when returning, you don't need the [], you only need return AnalyzerInts

Finally, you need to initialize your array to contain 5 elements not 4: int[] AnalyzerInts = new int[5];

Comments