本次实验是字符串的倒序排列, 在 C 语言中对字符串的操作可以说是无处不在, 其作用不言而喻. 下面就用 2 种不同的方法对字符串进行倒序排列.
一, 实验程序
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- /* 方法一:*/
- static int string_t1(void)
- {
- char *str = {"Hello, world!"};
- printf("before:%s\n", str);
- int len = strlen(str);
- char * std = (char *)malloc(len+1); /* 要多分配一个空间 */
- char *p = std;
- char *s = &str[len-1];/* 指向最后一个字符 */
- while(len-- != 0)
- {
- *p++ = *s--;
- }
- *p = '\0'; /* 尾部要加'\0'*/
- printf("after:%s\n", std);
- free(std); /* 使用完, 应该释放空间, 以免造成内存泄漏 */
- std = NULL; /* 防止产生野指针 */
- }
- /* 方法二:*/
- static int string_t2(void)
- {
- char t;
- char str[] = "Are you ok!";
- printf("before:%s\n", str);
- //int len = sizeof(str)-1;
- int len = strlen(str);
- for(int i = 0; i < len/2; i++)
- {
- t = str[i];
- str[i] = str[len-i-1];
- str[len-i-1] = t;
- }
- printf("after:%s\n", str);
- }
- int main(int argc, char const *argv[])
- {
- string_t1();
- string_t2();
- return 0;
- }
二, 实验结果
说明: 实验编译环境 Ubuntu, 如果没有安装 Ubuntu 或者 CentOS, 在网上自行下载 VC++6.0 中文版或者 Visual Studio(VS2013) 进行安装后编译.
来源: https://www.cnblogs.com/lyiwei/p/11741362.html