I have problem to output text in sentence case characters. When I prompt: heLLo! heLLo. i am OKAY.
I'm expecting output: Hello! Hello. I am okay.
But my sample run output is: Hello! hello. i am okay.
My code cannot output uppercase after '!'/'.'/'?'/'_' Anybody can advise what mistake that I made? Thanks in advance.
-Ellie
Sample code:
printf ("\n\nThe line of the text in sentence case is:\n");
i = 0;
text_ptr = text;
up = 1; /* up = 1 means upper case is yes */
while ( *(text_ptr+i) != '\0') /* could have been: while(text[i]) */
{
if(!up)
if( *(text_ptr+i-1)==' ' && toupper(*(text_ptr+i)=='I' && (*(text_ptr+i+1)==' ' ||
*(text_ptr+i+1)=='.' || *(text_ptr+i+1)=='!' || *(text_ptr+i+1))=='?') )
up = 1; /* capitalize i if all alone */
if(up)
if (*(text_ptr+i)!=' ' || *(text_ptr+i+1)=='.' || *(text_ptr+i+1)=='!' || *(text_ptr+i+1)=='?')
{
putchar(toupper(*(text_ptr++)));
up = 0;
} /* end if */
else
putchar(tolower(*(text_ptr++)));
else
{
putchar(tolower(*(text_ptr+i)));
if (*(text_ptr)=='?' || *(text_ptr)=='.' || *(text_ptr)=='!')
up = 1;
i++;
} /* end else */
}/* end while */`
Once again. After starring a bit more at the code I saw that
text_ptr++
i
only in the else
part of the looptext_ptr++
and text_ptr+i
... what is hard to understand So I completely revised my version:
int i = 0;
int up = 1; /* up = 1 means next char should be upper case*/
char* text_ptr = text;
while (*(text_ptr+i) != '\0') { /* could have been: while(text[i]) */
if(!up)
if(*(text_ptr+i-1)==' ' && toupper(*(text_ptr+i))=='I' &&
(*(text_ptr+i+1)==' ' || *(text_ptr+i+1)=='.' || // fix bracket here
*(text_ptr+i+1)=='!' || *(text_ptr+i+1)=='?')) { // "i" foll. by one of those
up = 1; /* capitalize i if all alone */
}
if(up)
if (*(text_ptr+i)!=' ' && *(text_ptr+i)!='.' && // fix here
*(text_ptr+i)!='!' && *(text_ptr+i)!='?') { // anything else than these
putchar(toupper(*(text_ptr+i))); // toupper and reset up
up = 0;
} /* end if */
else
putchar(tolower(*(text_ptr+i))); // just print
else
{
putchar(tolower(*(text_ptr+i)));
if (*(text_ptr+i)=='?' || *(text_ptr+i)=='.' || *(text_ptr+i)=='!')
up = 1;
} /* end else */
i++;
}/* end while */
Note that this version does require the toupper
again. Otherwise correct I
will be lowered. Your fourth if
works fine as well (I oversaw, that you don't reset the up
flag for spaces).