- 1
(Edit: Solved) Why do I get an IndexOutOfBoundsException?
I use an array a containing the English alphabet to get the index of a char in a string and then I access the value of an array b, containing the reversed version of a. My code should be below the post. Also using Array.Reverse(arrayName) does nothing, quite literally, no matter how I use it. At this point I am totally lost and feel like this bug is only here in SoloLearn. I've searched the Internet and have found nothing helpful. Help would be greatly appreciated https://code.sololearn.com/c2U8wIo4Bs92/?ref=app
5 odpowiedzi
+ 5
in your forEach loop you test if lowercased char is in alphabet, but then you search index of unmodified char... that is, if you get an uppercased char, you will search index of uppercased char instead of lowercased: that's why you get error ^^
if (alphabet.Contains(char.ToLower(c)))
{
index = Array.IndexOf(alphabet,char.ToLower(c));
+ 3
visph and ChaoticDawg thank you for your answers. That indeed was the problem and now it's working great
+ 2
You can also work directly with the strings in the same manner as you are after you convert to arrays.
static void Main(string[] args)
{
string input = Console.ReadLine().ToLower();
string output = "";
string alphabet = "abcdefghijklmnopqrstuvwxyz";
string reverseAlphabet = "zyxwvutsrqponmlkjihgfedcba";
int index = 0;
foreach (char c in input)
{
if (alphabet.Contains(c))
{
index = alphabet.IndexOf(c);
output += reverseAlphabet[index];
}
else
{
output += c;
}
}
Console.WriteLine(output);
}
+ 1
I entered my name "avinesh" and it gave me "zermvhs" which is what you were trying to get I guess.
What's the bug?
Share a particular instance where you are finding this error. Someone might help.
0
Avinesh I am trying to complete the code coach challenge "Secret Message" and the second test case and onwards all fail because of that IndexOutOfBoundsException