The code is supposed to reverse the words that have the length equal to longest word length from the phrase.
Input string: #Voi#da#bacu#la#info#
Expected output string: #Voi#da#ucab#la#ofni#
I observed that if I replace this condition:
while (position < sentenceLength - 1) { ... }
With this one:
while (position < strlen(sentence) - 1) { .... }
The while loop is not executed. Why is that?
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstring>
using namespace std;
int main() {
char sentence[101];
cin.getline(sentence, 101);
int sentenceLength = strlen(sentence);
char sentenceCopy[101];
strcpy(sentenceCopy, sentence);
int maxLength = -1;
char* wordPtr = strtok(sentenceCopy, "#");
while (wordPtr != NULL) {
int wordLength = strlen(wordPtr);
if (wordLength > maxLength) {
maxLength = wordLength;
}
wordPtr = strtok(NULL, "#");
}
int position = -1;
while (position < sentenceLength - 1) {
position++;
if (sentence[position] == '#') {
continue;
}
int currentLength = 0;
int left = position;
int right = position;
while (sentence[right] != '#' && right < sentenceLength) {
right++;
currentLength++;
}
position = right;
right--;
if (currentLength == maxLength) {
while (left < right) {
char temp = sentence[left];
sentence[left] = sentence[right];
sentence[right] = temp;
left++;
right--;
}
}
}
cout << sentence;
return 0;
}
strlenreturns asize_t, which is unsigned.sentenceLengthis anint.strlenisunsigned.Ccoding. See this.