Java 把数字和字符串分开

Java 把数字和字符串分开,java,Java,我想得到给定字符串的数字,我使用的代码如下 String sample = "7011WD"; String output = ""; for (int index = 0; index < sample.length(); index++) { if (Character.isDigit(sample.charAt(index))) { char aChar = sample.charAt(index);

我想得到给定字符串的数字,我使用的代码如下

String sample = "7011WD";
    String output = "";
    for (int index = 0; index < sample.length(); index++)
    {
        if (Character.isDigit(sample.charAt(index)))
        {
            char aChar = sample.charAt(index);
            output = output + aChar;
        }
    }

    System.out.println("output :" + output);
结果是: 产出:7011

有什么简单的方法可以得到输出吗

有什么简单的方法可以得到输出吗

可能您可以使用正则表达式\\D+D是非数字的任何东西,+表示一次或多次出现,然后是所有非数字的空字符串:

String sample = "7011WD";
String output = sample.replaceAll("\\D+","");
尽管要记住,使用正则表达式一点效率都没有。此外,这个正则表达式也将删除小数点

您需要分别使用或来获取原语int或long

您也可以使用。使用指定范围,并使用以字符串形式按顺序返回该范围中的字符

有什么简单的方法可以得到输出吗

可能您可以使用正则表达式\\D+D是非数字的任何东西,+表示一次或多次出现,然后是所有非数字的空字符串:

String sample = "7011WD";
String output = sample.replaceAll("\\D+","");
尽管要记住,使用正则表达式一点效率都没有。此外,这个正则表达式也将删除小数点

您需要分别使用或来获取原语int或long


您也可以使用。使用指定范围,并使用将该范围中的字符按顺序作为字符串返回。

您也可以使用ASCII来执行此操作

String sample = "7011WD";
String output = "";
for (int index = 0; index < sample.length(); index++)
{

        char aChar = sample.charAt(index);
        if(int(aChar)>=48 && int(aChar)<= 57)
        output = output + aChar;
    }
}

System.out.println("output :" + output);

您也可以使用ASCII来完成此操作

String sample = "7011WD";
String output = "";
for (int index = 0; index < sample.length(); index++)
{

        char aChar = sample.charAt(index);
        if(int(aChar)>=48 && int(aChar)<= 57)
        output = output + aChar;
    }
}

System.out.println("output :" + output);

这个代码似乎有效。问题是什么?检查一下现有的类似这样的帖子,代码似乎可以工作。问题是什么?检查一下现有的帖子,如果你真的想得到一个整数,就用整数吧。parseIntoutput@RobertKotcher我会加上的!我认为\D匹配非数字字符,请澄清。是的,用空字符串替换所有非数字!如果您实际上想要得到一个整数,请使用integer。parseIntoutput@RobertKotcher我会加上的!我认为\D匹配非数字字符,请澄清。是的,用空字符串替换所有非数字!OP要求用一种更简单的方法来解决这个问题,我不确定这是否符合这些指导原则。OP要求用一种更简单的方法来解决这个问题,我不确定这是否符合这些指导原则。