我需要提取给定字符串中的数字并将它们存储在一个单独的数组中,以便每个索引在字符串中存储一个单独的数字。 前 - " 15只狐狸追逐12只兔子"。我需要将数字15和12存储在[0]和[1]中。
String question=jTextArea1.getText();
String lower=question.toLowerCase();
check(lower);
public void check(String low)
{
int j;
String[] ins={"into","add","Insert"};
String cc=low;
for(int i=0;i<2;i++)
{
String dd=ins[i];
if(cc.contains(dd))
{
j=1;
insert(cc);
break;
}
}}
public void insert(String low)
{
String character = low;
int l=low.length();
int j[]=new int[20];
int m=0;
for(int k=0;k<=2;k++)
{
j[k]=0;
for(int i=0;i<l;i++)
{
char c = character.charAt(i);
if (Character.isDigit(c))
{
String str=Character.toString(c);
j[k]=(j[k]*10)+Integer.parseInt(str);
m++;
}
else if (Character.isLetter(c))
{
if(m>2)
{
break;
}
}}}
答案 0 :(得分:1)
正则表达式是您的最佳选择。
//Compilation of the regex
Pattern p = Pattern.compile("(\d*)");
// Creation of the search engine
Matcher m = p.matcher("15 foxes chases 12 rabbits");
// Lunching the searching
boolean b = m.matches();
// if any number was found then
if(b) {
// for each found number
for(int i=1; i <= m.groupCount(); i++) {
// Print out the found numbers;
// if you want you can store these number in another array
//since m.group is the one which has the found number(s)
System.out.println("Number " + i + " : " + m.group(i));
}
}
您必须导入java.util.regex。*;
答案 1 :(得分:0)
假设你不能像Collection
一样使用List
,我首先要分割白色空间,使用一种方法来计算该数组中的数字({{3}在数字上),然后构建输出数组。像
public static int getNumberCount(String[] arr) {
int count = 0;
for (String str : arr) {
if (str.matches("\\d+")) {
count++;
}
}
return count;
}
然后像
一样使用它public static void main(String[] args) {
String example = "15 foxes chases 12 rabbits";
String[] arr = example.split("\\s+");
int count = getNumberCount(arr);
int[] a = new int[count];
int pos = 0;
for (String str : arr) {
if (str.matches("\\d+")) {
a[pos++] = Integer.parseInt(str);
}
}
System.out.println(Arrays.toString(a));
}
输出(按要求)
[15, 12]
答案 2 :(得分:0)
要从字符串中提取数字,请使用以下代码:
String text = "12 18 100";
String[] n = text.split(" ");
int[] num = n.length;
for (int i =0; i < num.length;i++) {
num[i] = Integer.parseInt(n[i]);
};
文本中的所有字符串数字都是整数
答案 3 :(得分:0)
我相信它应该是
String str = "12 aa 15 155";
Scanner scanner = new Scanner( str );
while( scanner.hasNext() )
{
if( scanner.hasNextInt() )
{
int next = scanner.nextInt();
System.out.println( next );
}
else
{
scanner.next();
}
}
scanner.close();