用C语言实现字符串反转函数strrev的经典方法 您所在的位置:网站首页 c语言中是如何实现字符串的 用C语言实现字符串反转函数strrev的经典方法

用C语言实现字符串反转函数strrev的经典方法

2024-01-08 04:08| 来源: 网络整理| 查看: 265

字符串反转函数strrev不是C语言标准库函数,很多C语言编译器并没有提供对它的支持,比如你在Linux下输入Shell命令man 3 strlen,屏幕上会显示,

STRLEN(3) Linux Programmer's Manual STRLEN(3) NAME strlen - calculate the length of a string SYNOPSIS #include size_t strlen(const char *s); DESCRIPTION The strlen() function calculates the length of the string s, excluding the terminating null byte ('\0'). RETURN VALUE The strlen() function returns the number of characters in s. CONFORMING TO SVr4, 4.3BSD, C89, C99. SEE ALSO string(3), strnlen(3), wcslen(3), wcsnlen(3) COLOPHON This page is part of release 3.35 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at http://man7.org/linux/man-pages/. GNU 2011-09-28 STRLEN(3) 告诉你strlen函数所实现的功能是calculate the length of a string,引用时需要#include 。而如果输入man 3 strrev命令,Shell会告诉你,

在第 3 节中没有关于 strrev 的手册页条目。通过以上操作,也验证了GCC没有提供对strrev的支持,由于它并属于标准函数,编译器有理由不支持的。

strrev函数不常用,不过在进行数制转换和加密等场合还是有机会用到,因为一些针对嵌入式平台的编译器和VC对它提供了支持。对于不支持strrev函数的编译器,许多网友提供了不少很有价值的解决方案,不过直接从VC所提供的源代码中去提炼,似乎更能够兼顾效率和移植性,以下提供一份经典的实现代码:

char* strrev(char* s) {     /* h指向s的头部 */     char* h = s;         char* t = s;     char ch;     /* t指向s的尾部 */     while(*t++){};     t--;    /* 与t++抵消 */     t--;    /* 回跳过结束符'\0' */     /* 当h和t未重合时,交换它们所指向的字符 */     while(h < t)     {         ch = *h;         *h++ = *t;    /* h向尾部移动 */         *t-- = ch;    /* t向头部移动 */     }     return(s); }



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有