Index was outside the bounds of the array | Sololearn: Learn to code for FREE!

+2

Index was outside the bounds of the array

Hi! i need to solve this - how many characters at the beginning of the string are mirrored to those at the end of the string When string is symmetric the index is out of rang, how to solve this? string word = Console.ReadLine(); char lastCharacter = word[word.Length - 1]; char first = word[0]; int count = 0; while (first == lastCharacter ) { if (first == lastCharacter) { count++; lastCharacter = word[word.Length - (count + 1)]; first = word[count]; } } Console.WriteLine(count);

c#

1/27/2022 12:21:31 PM

Bogdan Parnete

8 Answers

New Answer

+3

Thank you ๐Ÿ˜๐Ÿ˜

+2

You are not stoping assigning values even when count reaches word.Length here lastCharacter = word[word.Length - (count + 1)]; first = word[count]; You are checking characters only but not paid attention to indexes!! before these add condition to break : if count>=word.Length) break;

+1

As people already said, you should include another stop condition on the indexes. Also: 1. You can AND both conditions (first == last and indexes within limits) in the while statement itself. No need for a if... break block. 2. Think again about why the if (first == last) inside a while (first == last) 3. Bonus: try also with a for loop and see what looks best.

0

You really should be playing with the indices. string word = Console.ReadLine(); int count = 0; for( int first = 0, last = word.Length - 1; first < last; first++, last-- ) { if (word[ first ] == word[ last ] ) { count++; } ) Console.WriteLine( count );

0

One question, if I type abcddddddcba , the sentence is symmetrical, in this case => 10 in console , no? In my case it displays 5

0

Well, 5 characters at the beginning of the string match 5 characters at the end of the string. So it matches your problem description. Put your updated code in code playground and link it inside the question with + button. This way we can see and evaluate changes.

0

string world = Console.ReadLine(); int first = 0; int last = world.Length - 1; int cout = 0; while (first < last) { if (world[first] == world[last]) { cout++; } first++; last--; } var reversed = new string(world.Reverse().ToArray()); if (world == reversed) { Console.WriteLine(world.Length); } else Console.WriteLine(cout); I sove it with palindrom method, what do you think ?

0

Now it doesn't match your problem description anymore. And the question doesn't have a link to code playground.