如何用C语言将字符串逆序输出?

如题所述

C语言程序如下:

#include<stdio.h>

#include<string.h>

main()

{

int i,j,t,n;

char a[10];

printf("请输入字符串:");

gets(a);

n=strlen(a);

for(i=0;i<=n/2;i++)

{

t=a[i];

a[i]=a[n-1-i];

a[n-1-i]=t;     

}

for(j=0;j<n;j++)

printf("%c",a[j]);

printf("\n"); 

扩展资料:

字符串倒序输出的五种方法

1、使用数组循环

2、StringBuffer的reverse方法

3、StringBuffer的循环  

4、栈的后进先出

5、迭代完成

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-02-27
//下面是C语言代码
#include <stdio.h>

int main(void)
{
    char* ch;
    scanf("%s",ch);
    int i=0,j;
    //while用来取得字符串的长度
    while(*(ch+i)!='\0')
    {
        i++;
    }
    //for循环从后向前访问字符串,其实就是字符数组
    for(j=i-1;j>=0;j--)
    {
        printf("%c",*(ch+j));
    }

    printf("\n");
    return 0;
}

原理:

C语言中对字符串进行操作,不仅仅对于字符数组,都可以用字符串的变量名来做该字符串的指针,其变量名指向第一个字符。因此,可以通过指针从后往前进行读取操作,从而实现逆序输出。

本回答被网友采纳
第2个回答  2020-02-05
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
char a,ap[10];
int i;

printf("请输入:");
scanf("%s",ap);
i = strlen (ap);

for(;i>=0;i--)
{
ap[i];
printf("%c",ap[i]);
}
system("pause");
return 0;
}
第3个回答  2018-01-26


#include <stdio.h>#include<stdlib.h>int main(void){    char* ch=(char*)malloc(100);    //不分配内存会出现段错误    scanf("%s",ch);    int i=0,j;       while(*(ch+i)!='\0')    {        i++;    }      for(j=i-1;j>=0;j--)    {        printf("%c",*(ch+j));    }     printf("\n");    return 0;}
第4个回答  2019-12-23
下面是C语言代码 #include <stdio.h> int main(void) { char* ch; scanf("%s",ch); int i=0,j; //while用来取得字符串的长度 while(*(ch+i)!='\0') { i++; } //for循环从后向前访问字符串,其实就是字符数组 for(j=i-1;j>=0;j--) { printf("%c",*(ch+j)); } printf("\n"); return 0; }原理: C语言中对字符串进行操作,不仅仅对于字符数组,都可以用字符串的变量名来做该字符串的指针,其变量名指向第一个字符。因此,可以通过指针从后往前进行读取操作,从而实现逆序输出。
相似回答