指针句大小写(C)

pointer sentence case (C)

我在以句子大小写字符输出文本时遇到问题。当我提示: 你好!你好。我还好。

我期待输出: 你好!你好。我没事。

但我的示例 运行 输出是: 你好!你好。我没事

我的代码无法在 '!'/'.'/'?'/'_' 后输出大写字母 任何人都可以建议我犯了什么错误?提前致谢。

-艾莉

示例代码:

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) != '[=10=]')  /* 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) != '[=10=]') { /* 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 标志)。