字符串逆置
来源:互联网 发布:怎样通过网络发短信 编辑:程序博客网 时间:2024/05/18 00:37
记录一下字符串逆置的代码:
此版用到了另一个字符数组,以保存逆置后的结果,开始时只是定义了两个字符指针来保存输入的字符串,编译总是失败,看了一下《C语言实用教程》里面说到,char *p scanf("%s",p);这种定义方式是错误的,指针需要先指向一个地址。于是就定义了两个字符数组来保存结果。这样定义一个常量N为50,但是感觉缺少了一些灵活性。
#include <stdio.h>#define N 50int main(){ int i, n=0; //char *str1, *str2; char str1[N], str2[N]; char *p=str1; printf("Please input the string:"); scanf("%s",str1); printf("The string you input is %s\n",str1); while(*p!='\0') { ++p; ++n; } for(i=0;i<n;++i) str2[i]=*--p; //printf("%c",*--str1); str2[i]='\0'; printf("The string reversed is %s\n",str2); return 0;}
#include <stdio.h>#include <string.h>#define N 50int main(){ int i,n; char str[N], temp; printf("Please input the string:"); scanf("%s",str); printf("The string you input is %s\n",str); n=strlen(str); for(i=0;i<n/2;++i) { temp=str[i]; str[i]=str[n-1-i]; str[n-1-i]=temp; } printf("The string reversed is %s\n",str); return 0;}
下面的版本将字符逆置写成一个函数。几天前看到CSDN论坛上的一个问题:定义一个函数 void strcpy(char *to, const char *from)反转字符串要求函数不可以用到库函数和其他变量,于是只针对to和from指针做操作,在反向遍历时用while做条件判断(不知道字符串第一个字符的前一个字符是什么,也许是NULL?),结果有一些问题。可以利用数组首地址调入函数直接操作。
#include <stdio.h>#define N 50//reverse copyvoid strcpy(char *to,const char *from){ while(*++from) ; while(*to++=*--from) ; while(*--to) ; ++to;}int main(){ char str1[N], str2[N]; //char *p1=str1, *p2=str2; printf("Please input the string:"); scanf("%s",str1); printf("The string you input is %s\n",str1); //strcpy(p2, p1); strcpy(str2,str1); printf("The string reversed is %s\n",str2); return 0;}
最后是一个C++的版本,受到网上一个思路的启发,在C++的算法库中有一个反转算法,只要传入迭代器参数即可,而且利用string库中的getline()函数可以实现带有空格字符串的逆置,非常之简洁。
#include <iostream>#include <string>//#include <iterator>#include <algorithm>using namespace std;int main(){ string str; cout<<"Please input a string you want to reverse:"<<endl; getline(cin,str); //string::iterator beg=str.begin(); //string::iterator end=str.end(); reverse(str.begin(),str.end()); cout<<"The string reversed is:"<<str<<endl; return 0; }
- 字符串内容逆置
- 字符串逆置
- 字符串逆置
- 字符串逆置
- 字符串逆置函数
- 字符串逆置问题
- 字符串逆置
- 逆置字符串
- 字符串逆置
- 逆置字符串
- 字符串逆置算法
- 字符串逆置算法
- 字符串大小写逆置
- 字符串大小写逆置
- 字符串分割,字符串拷贝,单词逆置,单词逆置
- 字符串逆置(转载)
- 字符串的就地逆置
- 字符串逆置(递归)
- 输入联想 输入关键字 显示下拉包含关键字的文字
- 上传图片 出现错误:413 Request Entity Too Large
- Servlet和Filter的url匹配以及url-pattern详解
- int,NSInteger,NSUInteger,NSNumber
- helper类
- 字符串逆置
- asp.net 把后台数据赋值给js的变量的方法
- BIOS中隐藏Telnet后门
- 1.CXF:简介
- 请问NSInteger与int有何不同
- 云计算将在2015年以前发展成熟
- 概要设计与详细设计的区别
- 由于p3006854_9204_linux.zip在Linux 5.5安装导致的错误解决办法
- 把一个shell程序编译成二进制可执行文件