如何在Java中分隔字符,数字和符号?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何在Java中分隔字符,数字和符号?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1778字,纯文字阅读大概需要3分钟。
内容图文
我有一个问题,我有一些字符串,像这样
?????? ?????? ???????? 1998 – ??????? 2009???????? ??????
是的,它们是用维吾尔语写的,很像阿拉伯语,我不知道维吾尔语.
我现在需要用空格,符号和数字来区分它们.
我用python尝试过,我可以得到这个结果.
?????? ????? ? ???????? 1998 – ??????? 2009 ???????? ??????
如果我忽略了很多空格,结果就是我想要的.
和python代码是
def re_str(matched):
replace_str = matched.group('symbol')
return ' ' + replace_str + " "
# test is the string above
print(re.sub('(?P<symbol>\W)', re_str, re.sub('(?P<symbol>\d+)', re_str, test)))
现在的问题是:我想用Java来实现这个效果,但我不知道怎么做?请帮我
我尝试使用Java,但它不起作用
String pattern = "(\\d+)|([\\p{P}\\p{S}]+)|\\W";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(test);
解决方法:
使用isAlphabetic和isDigit的组合,否则你有一个特殊的角色.
public class Separater {
static String splitString(String str) {
String result = "";
int i=0;
while (i < str.length()) {//Using while instead of for, to avoid skipping characters due to auto increment by the loop.
if (Character.isDigit(str.charAt(i))) {
while (i < str.length() && Character.isDigit(str.charAt(i))) {
result += str.charAt(i);
i++;
}
result += " ";
} else if (Character.isAlphabetic(str.charAt(i))) {
while (i < str.length() && Character.isAlphabetic(str.charAt(i))) {
result += str.charAt(i);
i++;
}
result += " ";
} else {
while (i < str.length() && !Character.isAlphabetic(str.charAt(i)) && !Character.isDigit(str.charAt(i))) {
result += str.charAt(i);
i++;
}
result += " ";
}
}
return result;
}
public static void main(String[] args) {
System.out.println(splitString("?????#*(???????678345?????*&&*^*!!??????"));
}
}
产量
请注意,子字符串之间的空间较大,但SO删除了额外的空格!
????? #*( ??????? 678345 ????? &&^*!! ??????
内容总结
以上是互联网集市为您收集整理的如何在Java中分隔字符,数字和符号?全部内容,希望文章能够帮你解决如何在Java中分隔字符,数字和符号?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。