请用 Java 写一个 String 处理方法,将输入字符串中的中文与英文、数字之间使用空格隔开,并针对特殊符号(括号和逗号)
3条回答 默认 最新
- fufeiwen 2017-08-02 01:47关注
package com.fufeiwen.test;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) { System.out.println(getStr("我是中国ren,nishi谁?")); } public static String getStr(String str) { String curStr; int preType = -1; StringBuffer sb = new StringBuffer(); for (int i = 0; i < str.length(); i++) { curStr = str.substring(i, i + 1); int curType = getType(curStr); if (i>0&&curType != preType) { sb.append(" "); } sb.append(curStr); preType=curType; } return sb.toString(); } public static int getType(String str) { String chinese = "^[\u4e00-\u9fa5]{0,}$"; String number = "^[0-9]*$"; String letter = "^[A-Za-z]+$"; int num = 0;//其他 if (Pattern.matches(chinese, str)) { num = 1;//中文 } else if (Pattern.matches(number, str)) { num = 2;//数字 } else if (Pattern.matches(letter, str)) { num = 3;//字母 } return num; }
}
以上是大体思路,没考虑性能、细节。
解决 无用评论 打赏 举报
悬赏问题
- ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
- ¥15 C# datagridview 单元格显示进度及值
- ¥15 thinkphp6配合social login单点登录问题
- ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
- ¥15 如何在scanpy上做差异基因和通路富集?
- ¥20 关于#硬件工程#的问题,请各位专家解答!
- ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
- ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
- ¥30 截图中的mathematics程序转换成matlab
- ¥15 动力学代码报错,维度不匹配