反转字符串--C和Python
2015-12-08 18:19
447 查看
将字符串反转,即“abcde”->"edcba"
C语言实现:
【转自http://www.kanzhun.com/mianshiti/456.html?sid=mail_18200_2_detail&ka=mail-18200-2-detail3】
Python实现
方法一:先把字符串转换成列表,利用列表的reverse方法反转列表,再用字符串的join方法连接列表
方法二:利用字符串的倒序切片 a[::-1]
C语言实现:
【转自http://www.kanzhun.com/mianshiti/456.html?sid=mail_18200_2_detail&ka=mail-18200-2-detail3】
#include <stdio.h> #include <stdlib.h> #include <string.h> int reverse(int i) { int flag; if(i > 0) { flag = 1; } else { flag = -1; } i *= flag; char *tmp = (char*)malloc(sizeof(char)*100); sprintf(tmp, "%d", i); printf("%s", tmp); int len = strlen(tmp); int j; char a; for(j = 0; j < len/2; ++j) { a = tmp[j]; tmp[j] = tmp[len-j-1]; tmp[len-j-1] = a; } i = atoi(tmp); i *= flag; free(tmp); return i; } int main(void) { int i; scanf("%d", &i); i = reverse(i); printf(" %d", i); return 0; }
Python实现
方法一:先把字符串转换成列表,利用列表的reverse方法反转列表,再用字符串的join方法连接列表
方法二:利用字符串的倒序切片 a[::-1]
相关文章推荐
- Python 基础【第六篇】字典
- python中,一个函数想使用另一个函数中的变量
- Python 基础【第五篇】元组和列表
- python实战系列之ip地址排序问题(二)
- Python序列切片的注意事项
- python tkinter MD5加密
- python之路:进阶篇
- python中的可变对象和不可变对象
- python爬取网页时去除html标签(如nbsp)
- Python 模版(四)
- python error
- python实战系列之模拟用户密码登陆系统(一)
- python之路: 基础篇
- [转]用python 10min手写一个简易的实时内存监控系统
- python 学习笔记
- 理解Python中的装饰器
- Python 模版(三)
- Python 模版(二)
- 使用Python编写简单的画图板程序的示例教程
- Python split()函数默认参数