将字符串转换为特殊字符串

时间:2015-11-15 14:56:03

标签: c string

输入: 你好

输出:

Olleh Ereht

输入:

你好吗?

输出:

Woh Era?你

 #include <stdio.h>
    #include <string.h>

int main()
{
   char s[100], r[100];
   int n, c, d=0;
   int p=0,t=0;

   printf("Input a string\n");
   gets(s);

   //n = strlen(s);

    while(s[p]!= '\0'){
        while(s[p]!= ' ' || s[p]!= '\0'){
            p++;
        }

        for (c = p-1; c >= t; c--, d++)
            r[d] = s[c];

        r[d++] = ' ';

     // printf("%s\n", r);
        t=p;
        p++;
    }

    r[d]= '\0';
    printf("%s\n", r);
    return 0;
}

我的时间限制超出问题..不知道我哪里出错了.Plz帮我解决了问题。

2 个答案:

答案 0 :(得分:1)

我认为内部while循环永远不会终止,因为条件永远不会给出错误。 要终止循环:

s [p]!='' s [p]!='\ 0'两者都应该为假。

也就是说

s [p] =='' s [p] =='\ 0'两者都应该为真,这是不可能的。

这就是为什么你得到超出时间限制的错误。

答案 1 :(得分:0)

也许就像这样

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void){
    char s[100], r[100];
    int p = 0, d = -1;

    printf("Input a string\n");
    scanf("%99[^\n]", s);//gets(s);<-- "gets" already was obsolete.

    while(1){
        if(s[p] != ' ' && s[p] != '\0'){
            r[++d] = s[p];
        } else {
            if(d >= 0){
                putchar(toupper(r[d--]));
                while(d >= 0){
                    putchar(tolower(r[d--]));
                }
            }
            if(s[p] == ' ')
                putchar(' ');
            else
                break;
        }
        ++p;
    }

    return 0;
}
相关问题