c语言-逆置字符串

    xiaoxiao2025-09-19  649

    #include "stdio.h" #include "string.h" int main() { char s[]="张伟伟"; int len=strlen(s); printf("%d\n",sizeof(s)); printf("%s\n",s); int start=0; int end=len-3; char *p =&s[0]; char *p1=&s[len-3]; while(start<end)//uft8三个字节组成一个汉字,逆置时候就要考虑到这点 { //下面代码 是1-7 2-8 3-9 进行交换 char tem=*p; *p=*p1; *p1=tem; p++; p1++; tem=*p; *p=*p1; *p1=tem; p++; p1++; tem=*p; *p=*p1; *p1=tem; p++; p1-=5; start+=3; end-=3; } printf("%s\n",s); }

    以下是字符串逆置

    #include "stdio.h" #include "stdlib.h" #include "string.h" #include "time.h" #include <sys/stat.h> void inverse(char *str)//字符串逆置 { char *p1 = str; char *p2 = str + strlen(str) - 1; while (p1 < p2) { char tmp = *p1; *p1 = *p2; *p2 = tmp; p1++; p2--; } } int main() { char buf[] = "abcdefg"; inverse(buf); printf("buf=%s\n", buf); } void inverse(char *str,int num)//字符串逆置指定逆直前几位 { char *p1 = str; char *p2 = str + num - 1; while (p1 < p2) { char tmp = *p1; *p1 = *p2; *p2 = tmp; p1++; p2--; } }
    转载请注明原文地址: https://ju.6miu.com/read-1302829.html
    最新回复(0)