c++拆分字符,不拆开中文

// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//
 
#include "stdafx.h"
#include <string.h>
#include <string>
#include <vector>
#include <iostream>
 
using namespace std;
 
 
std::wstring GBKToUnicode(const std::string& src)
{
	setlocale(LC_ALL, "chs");// 设置为中文环境,不然可能会转换失败
	std::vector<wchar_t> dst(src.size() + 1, L'\0');
	size_t count = std::mbstowcs(&dst[0], src.c_str(), dst.size() - 1);
	setlocale(LC_ALL, "C");
	return std::wstring(&dst[0]);
}
 
 
// 判断字符串是否有中文
bool hasChinese(const std::string& src, int* array)
{
	auto w = GBKToUnicode(src);
	int i = 0;
	for (auto c : w)
	{
		if (c >= 0x4E00 && c <= 0x9FCB || c >= 0x3400 && c <= 0x4DB5)
		{
			array[i++] = 1;
			//i++;	// 向后延一位
		}
 
		i++;
	}
 
	return false;
}
 
 
int splitText(char* text, int len)
{
	if (NULL == text)
	{
		return 0;
	}
	
	int arr[1024]; memset(arr, 0x00, sizeof(arr));
	hasChinese(text, arr);
	char temp[1024]; memset(temp, 0x00, sizeof(temp));
	int text_len = (int)strlen(text);
	int j = 0;
	for (int i = 0; i < text_len; i++)
	{
		if (j >= len)
		{
			if (arr[i-1] == 1)
			{
				temp[j++] = text[i++];
			}
 
			printf("%s\n", temp);
			j = 0;
			memset(temp, 0x00, sizeof(temp));
		}
 
		temp[j++] = text[i];
 
	}
 
	printf("%s\n", temp);
 
 
	return 0;
}
 
 
 
int main(){
 
//	wcout << hasChinese("中国123他们是谁21423") << endl;
	splitText("中国123他们是谁21423", 5);
	return 0;
}
 
 
 
 
 
 
 
//// 中文的ascii为负数
//int splitText(char* text, int len)
//{
//	if (NULL == text)
//	{
//		return 0;
//	}
//
//
//	char text_temp[1024]; memset(text_temp, 0x00, sizeof(text_temp));
//	strcpy_s(text_temp, text);
//
//	int text_len = (int)strlen(text);
//	int j = 0;
//	char temp[1024]; memset(temp, 0x00, sizeof(temp));
//	for (int i = 0; i < text_len; i++)
//	{
//		if (j >= len)
//		{
//			if ((text[i - 1] & 0x80) == 0) {   //ascii begin with 0 
//
//			}
//			else
//			{
//				////如果字符高位为1且下一字符高位也是1则有中文字符
//				//if ((text[i - 1] & 0x80) && (text[i] & 0x80))
//				unsigned char text_i_1 = (unsigned char)text[i - 1];
//				unsigned char text_i = (unsigned char)text[i];
//
//				int high = text_i << 8;
//
//
//				int c = high + text_i_1;
//
//
///*				if (((text_i_1 >= 0) && (text_i_1 <= 0xCB) && (text_i >= 0x4E) && (text_i <= 0x9F)) ||
//					((text_i_1 >= 0) && (text_i_1 <= 0xB5) && (text_i >= 0x34) && (text_i <= 0x4D)))*/
//				if (c >= 0x4E00 && c <= 0x9FCB
//					|| c >= 0x3400 && c <= 0x4DB5)
//				{
//					temp[j] = text[i++];
//				}
//			}
//
//
//			printf("%s\n", temp);
//			j = 0;
//			memset(temp, 0x00, sizeof(temp));
//			//continue;
//		}
//
//		temp[j++] = text[i];
//		printf("%d %s\n", i, temp);
//
//	}
//	printf("%s\n", temp);
//	return 0;
//}
 

参考网站:https://www.zhihu.com/question/57479676/answer/153052641

posted @ 2018-04-22 13:51  雪域蓝心  阅读(390)  评论(0编辑  收藏  举报