我以句子大小写字符输出文本时遇到问题。当我提示时:你好!你好。我没事。
我期待输出:你好!你好。我没事。
但我的示例运行输出是:你好!你好。我没事。
我的代码无法在"!"之后输出大写字母/'.'/'?'/'_'任何人都可以建议我犯了什么错误?提前谢谢。
-艾莉
示例代码:
printf ("nnThe 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) != ' ') /* 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 */`
再一次。在多看了一会儿代码后,我看到
- 您操纵了指针
text_ptr++
- 仅在循环的
else
部分递增i
- 印刷
text_ptr++
和text_ptr+i
。什么很难理解 所以我完全修改了我的版本:
int i = 0;
int up = 1; /* up = 1 means next char should be upper case*/
char* text_ptr = text;
while (*(text_ptr+i) != ' ') { /* 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 */
请注意,此版本确实需要再次toupper
。否则,正确的I
将被降低。您的第四if
也可以正常工作(我监督过,您不会重置空格的up
标志)。