Samuël Búrns Samuël Búrns - 1 year ago 102
C# Question

Returning an Int Array from a Custom String Method?

I am creating a custom method that returns

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]))
else if (char.IsLower(input[x]))
else if (char.IsWhiteSpace(input[x]))
else if (char.IsPunctuation(input[x]))
return AnalyzerInts;

Answer Source

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];

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download