实现含有中文字符的字符串逆转

实现含有中文字符的字符串逆转,如: “我是小萌新” 转换成“新萌小是我”

第一版只支持中文:

#include <iostream>
#include <Windows.h>
#include <string>

using namespace std;

void ni_zeng_str(string &str, int len) {
	int lenth = len;

	for (int i = 0; i < lenth / 2; i += 2, len -= 2) {
		int ret = str[i];
		str[i] = str[len - 2];
		str[len - 2] = ret;

		ret = str[i + 1];
		str[i + 1] = str[len - 1];
		str[len - 1] = ret;
	}
}
int main(void) {
	string str;

	cout << "请输入中文字符串:";
	cin >> str;

	int len = str.length();
	ni_zeng_str(str, len);
	
	cout << "逆转后:" << str << endl;

	system("pause");
	return 0;
}

第二版支持数字、中文、英文字符:

#include <stdio.h>
#include <iostream>
#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 << "str len:" << 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(void) {
	unsigned char str[] = "我a是b小c萌d新";
	reverse(str);
	printf("result:%s\n", str);

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ZengYong12138/article/details/106749680
今日推荐