请用 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 安装svn网络有问题怎么办
- ¥15 Python爬取指定微博话题下的内容,保存为txt
- ¥15 vue2登录调用后端接口如何实现
- ¥65 永磁型步进电机PID算法
- ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
- ¥88 找成都本地经验丰富懂小程序开发的技术大咖
- ¥15 如何处理复杂数据表格的除法运算
- ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
- ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
- ¥15 latex怎么处理论文引理引用参考文献