java中提取字符串中的数字
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class NumberSplit {
public StringBuffer getString(String str) {
StringBuffer strbuf = new StringBuffer("t");
boolean flag = true;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// 判断是否是数字
if (c >= '0'&& c <= '9') {
// 判断和字符串中的数字是否重复
for (int j = 1; j < strbuf.length(); j++) {
if (c == strbuf.charAt(j)) {
// 如果重复,标志位数值为false,并跳出循环;否则标志位设置为true.
flag = false;
break;
} else
flag = true;
}
// 只有在即是数字又不重复的情况下才将改字符拼接到字符串上.
if (flag) {
strbuf.append(c);
}
}
}
return strbuf;
}
public static void main(String args[]) throws Exception {
System.out.println("请输入一段字符串,并以回车结束");
BufferedReader buf = new BufferedReader(
new InputStreamReader(System.in));
String str = buf.readLine();
StringBuffer strbuf = new NumberSplit().getString(str);
// 将返回的StringBuffer转换为字符数组
char c[] = strbuf.deleteCharAt(0).toString().toCharArray();
// 对字符数组排序
Arrays.sort(c);
// 输出字符数组
for (int i = 0; i < strbuf.length(); i++) {
System.out.print(c[i]);
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class NumberSplit {
public StringBuffer getString(String str) {
StringBuffer strbuf = new StringBuffer("t");
boolean flag = true;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// 判断是否是数字
if (c >= '0'&& c <= '9') {
// 判断和字符串中的数字是否重复
for (int j = 1; j < strbuf.length(); j++) {
if (c == strbuf.charAt(j)) {
// 如果重复,标志位数值为false,并跳出循环;否则标志位设置为true.
flag = false;
break;
} else
flag = true;
}
// 只有在即是数字又不重复的情况下才将改字符拼接到字符串上.
if (flag) {
strbuf.append(c);
}
}
}
return strbuf;
}
public static void main(String args[]) throws Exception {
System.out.println("请输入一段字符串,并以回车结束");
BufferedReader buf = new BufferedReader(
new InputStreamReader(System.in));
String str = buf.readLine();
StringBuffer strbuf = new NumberSplit().getString(str);
// 将返回的StringBuffer转换为字符数组
char c[] = strbuf.deleteCharAt(0).toString().toCharArray();
// 对字符数组排序
Arrays.sort(c);
// 输出字符数组
for (int i = 0; i < strbuf.length(); i++) {
System.out.print(c[i]);
}
}
import java.util.regex.Matcher;
public class test
{
public static void main(String args[]){
String str="abc12jlskdf4a";
Pattern p = Pattern.compile("[0-9\\.]+");
Matcher m = p.matcher(str);
while(m.find()){
System.out.print(m.group()+",");
}
}
}
希望对你有帮助
System.out.println(sss.replaceAll("\\D+", ""));
String[] mstr=str.split("[A-Za-z]");
String outstr="";
for (String string : mstr) {
if(string.matches("\\d+")){
outstr+=string+",";
}
}
outstr=outstr.substring(0,outstr.length()-1);
System.out.println(outstr);
你可以测试下~~结果和你的一样