posts - 137,comments - 0,views - 40654

设指针p1指向初始字符串s,再新建一个字符串tmp用来存放逆转后的字符。此时可以把p1和tmp看成两条链表,指针p2为实现逆转的中转站,p2的长度为tmp和s的长度之和,接下来就通过链表的特性把p1和p2的值进行逆转。

复制代码
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;

void reverse(unsigned char* s) {
    int len = strlen((char*)s);
    unsigned char tmp[1024];

    unsigned char* p1 = s;
    unsigned char* p2 = tmp + len;

    cout << "strlen:" << len << endl;

    *p2-- = 0;
    while (*p1){
        if (*p1 <= 'z') {  //ASCII字符,一般都是小于等于127,即非汉字字符
            *p2-- = *p1++;
        }
        else {   //汉字字符的逆转
            *(p2 - 1) = *p1++;
            *p2 = *p1++;
            p2 -= 2;
        }
    }
    for (int i = 0; i < len; i++) {
        s[i] = tmp[i];
    }
}
int main() {
    unsigned char str[128];
    cout << "请输入一串字符:";
    cin >> str;
    reverse(str);
    cout << "result:" << str << endl;

    system("pause");
    return 0;
}
复制代码

 

 

 

posted on   wshidaboss  阅读(120)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示