+ 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);

27th Jan 2022, 12:21 PM
Bogdan Parnete
Bogdan Parnete - avatar
8 ответов
+ 3
Thank you 😁😁
27th Jan 2022, 12:59 PM
Bogdan Parnete
Bogdan Parnete - avatar
+ 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;
27th Jan 2022, 12:43 PM
Jayakrishna 🇮🇳
+ 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.
27th Jan 2022, 1:03 PM
Emerson Prado
Emerson Prado - avatar
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 );
27th Jan 2022, 12:57 PM
Ipang
0
One question, if I type abcddddddcba , the sentence is symmetrical, in this case => 10 in console , no? In my case it displays 5
27th Jan 2022, 1:46 PM
Bogdan Parnete
Bogdan Parnete - avatar
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.
27th Jan 2022, 2:07 PM
Emerson Prado
Emerson Prado - avatar
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 ?
27th Jan 2022, 6:18 PM
Bogdan Parnete
Bogdan Parnete - avatar
0
Now it doesn't match your problem description anymore. And the question doesn't have a link to code playground.
27th Jan 2022, 8:27 PM
Emerson Prado
Emerson Prado - avatar