尝试使用c来反转字符串

时间:2014-04-06 12:44:44

标签: c

平台:C

您好,    我试图以下列格式反转字符串:

输入字符串:这是一只猫

输出字符串:siht si a tac

我实施的代码是:

int main()
{

    char str[100];
    char final[100];
    int len=0;
    int i=0;
    char temp[100];
    int j=0;

    printf("Enter the string");
    gets(str);
    len = strlen(str);

    printf("%s",str);


    for(j=0,i=len-1;i>0;i--)
    {
        while(j>=len-1)
        {
            temp[j] = str[i];
            final[j] = temp[j];
            j++;
        }            
    }

    printf("%s",final);       


    putchar('\n');

    getch();

}

有什么建议我做错了吗?

2 个答案:

答案 0 :(得分:1)

#include <stdio.h>
#include <ctype.h>
#include <conio.h> //for getch()

int main(){
    char str[100];
    char final[100];
    char temp[100];
    int i, j, k;

    printf("Enter the string :");
    scanf("%99[^\n]", str);

    printf("\n%s\n", str);

    for(k=j=i=0;;++i){
        if(isspace(str[i]) || str[i]=='\0'){
            while(k){
                final[j++] = temp[--k];
            }
            if('\0' == (final[j++] = str[i]))
                break;
            //k=0;
        } else {
            temp[k++] = tolower(str[i]);
        }
    }

    printf("%s\n", final);     

    getch();
    return 0;
}

答案 1 :(得分:0)

你设置j=0(实际上,你这样做了两次:一次是声明,一次是for-loop初始化器)。所以,j>=len-1不太可能是真的。因此,while循环不执行任何操作。结果,for循环也没用。你的整个程序包括一个提示,回声和无操作。