赞
踩
函数1:
- function result = splitChinese(label)
- % label为char类型字符
-
- % 确定汉字的位置
- log = arrayfun(@(x) (x >= '一' && x <= '龥'),label);
-
- % 初始状态为第一个字符和对应的逻辑值
- currentChar = label(1);
- currentLog = log(1);
- % 汉字到非汉字变化的次数;再+1就是分割的段数
- changeCount = sum(diff(log) ~= 0);
- result = cell(changeCount+1,1);
- N = 1;
- % 开始遍历字符数组和逻辑数组
- for i = 2:length(label)
- if log(i) == currentLog
- currentChar = [currentChar, label(i)];
- else
- % 将当前字符存储在结果数组中
- result{N} = currentChar;
-
- % 更新当前字符和对应的逻辑值
- currentChar = label(i);
- currentLog = log(i);
-
- N = N+1;
- end
- end
- % 加载最后一段字符
- result{N} = currentChar;
- end
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
函数2: 避免循环,更少的代码
- function result = splitChinese2(label)
- % label为char类型字符
-
- % 确定汉字的位置
- log = arrayfun(@(x) (x >= '一' && x <= '龥'),label);
- Indxs = find(diff(log) ~= 0);
-
- % 分割中文、英文字符
- result.Data = arrayfun(@(x,y) extractBetween(label,x,y),[0 Indxs]'+1,[Indxs length(label)]');
- result.flag = [log(Indxs),log(end)]; % 中文字段标记为1
-
- end
运行结果:
- label = '你好hello哈哈werweh反对131';
- result1 = splitChinese(label)
- result2 = splitChinese2(label)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。