请用 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 fluent的在模拟压强时使用希望得到一些建议
- ¥15 STM32驱动继电器
- ¥15 Windows server update services
- ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
- ¥15 模糊pid与pid仿真结果几乎一样
- ¥15 java的GUI的运用
- ¥15 Web.config连不上数据库
- ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
- ¥15 怎么配置广告联盟瀑布流
- ¥15 Rstudio 保存代码闪退