设指针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 < 0x80) { //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; }标签:tmp,p2,p1,unsigned,汉字,char,C++,字符串,逆转 From: https://www.cnblogs.com/smartlearn/p/16754043.html