字符串逆置

来源:互联网 发布:怎样通过网络发短信 编辑:程序博客网 时间: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;}


下面的版本是在一个字符串内部进行逆置,利用一个临时变量temp保存字符。

#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; }

原创粉丝点击