字符串逆置算法

1,输人:字符串”123456“

      输出:”654321“。

    注意:字符数组不等于字符串,只有当字符数组结尾加上结束标志’\0’,才是字符串。所以字符串用字符数组来初始化时,结尾必须加上’\0’。比如  初始化字符串   char ch[7]={‘1′,’2′,’3′,’4′,’5′,’6′,’\0’}。


   代码如下:

  

#include<stdio.h>
#include<string.h>
#include<malloc.h>
#define MAXSIZE 100
void invert(char ch[],int n)
{
	int i;
	char temp;
	for(i=0;i<n/2;i++)
	{
		temp=ch[i];
		ch[i]=ch[n-1-i];
		ch[n-1-i]=temp;
	}
}

void main()
{
 char s[MAXSIZE];
 char d[]={'1','2','3','4','5','6','\0'};//必须加上结束标志,因为这里字符数组不等于字符串,
 printf("***********************\n");//只有结尾加上了'\0',才是字符串。所以要想把d按照字
 printf(" 字符串逆置算法 \n");//符串打印,必须在结尾加上'\0'。
 printf("***********************\n");
 printf("\n");
 invert(d,6);
 printf("%s",d);
 printf("\n");
}

运行结果如下:

《字符串逆置算法》

    原文作者:yychenxie21
    原文地址: https://blog.csdn.net/chenxieyy/article/details/48296217
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞