将字符串拆分为数字数据和其他非数字数据

时间:2016-02-18 11:38:43

标签: java arrays string

我正在读取字符串数组的帐户详细信息(帐户名称和帐户余额)。典型值类似于{"Cash on hand -4871266","SB Account 976369","Current Account 980980"}。我想将字符串数组拆分为两个 - 第一个数组应包含帐户名,第二个数组应包含帐户余额。我不能基于空格拆分数组,因为帐户名可能包含空格。我怎样才能在Java中实现这一目标

3 个答案:

答案 0 :(得分:1)

您可以使用substring()进行拆分,使用lastIndexOf()来获取最后一个空间索引。

String x[] = {"Cash on hand -4871266","SB Account 976369","Current Account 980980"};
String arr1[] = new String[x.length], arr2[] = new String[x.length];

for(int i=0; i<x.length; i++)
{
    arr1[i] = x[i].substring(0,x[i].lastIndexOf(" ")); //account name
    arr2[i] = x[i].substring(x[i].lastIndexOf(" ")+1); //value
}

答案 1 :(得分:0)

如果帐户名称不包含数字,那么您可以使用模式-?\\d+去除金额

Pattern p = Pattern.compile("-?\\d+");
String[] accounts = {"Cash on hand -4871266","SB Account 976369","Current Account 980980"};
for(String account :  accounts){
    Matcher m = p.matcher(account);
    while (m.find()) {
      System.out.println(m.group());
    }
}

答案 2 :(得分:0)

尝试以下方法:

public class Main {

    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();

        stringList.add("Cash on hand -4871266");
        stringList.add("SB Account 976369");
        stringList.add("Current Account 980980");

        for (String str : stringList) {
            // Extracts the left hand-side of your string
            System.out.println(str.replaceAll("[\\s-+][0-9]+", ""));
            // Extracts the right hand-side of your string
            Pattern testPattern = Pattern.compile("[\\s-+][0-9]+");
            Matcher matcher = testPattern.matcher(str);
            matcher.find();
            System.out.println(matcher.group().trim());
        }
    }

}