什么是字符串转换程序,如a2b4c5到java语言的aabbbbccccc?

时间:2015-10-24 05:37:06

标签: java string

我得到了这个程序,但是我无法处理它,请有人告诉我如何以一种简单的方式处理它。谢谢

2 个答案:

答案 0 :(得分:-1)

使用以下代码,您可以从字符串中获取数字:

public static void main(String[] args)  {
    String str = "a2bc45cd5";

    Matcher m = Pattern.compile("\\d+").matcher(str);
    List<Integer> numbers = new ArrayList<Integer>();
    while(m.find()) {
      numbers.add(Integer.parseInt(m.group()));
    }
    System.out.println(numbers);

    Matcher m1 = Pattern.compile("[A-z]+").matcher(str);
    List<String> string = new ArrayList<String>();
    while(m1.find()) {
      string.add(m1.group());
    }

    System.out.println(string);
}


//Output :

[2, 45, 5] // For numbers
[a, bc, cd] // For string

使用循环获取数字后,您将获得输出结果。

答案 1 :(得分:-1)

公共课程计划{

/**
 * @param args
 */

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String str = "a11b4c5";
    System.out.println(getAnswerByPassingString(str));

}

public static String getAnswerByPassingString(String str) {
    String number = "";
    String letter = "";
    String resStr = "";
    ArrayList<String> stringList = new ArrayList<String>();
    ArrayList<String> numbersList = new ArrayList<String>();

    for (int i = 0; i < str.length(); i++) {
        char a = str.charAt(i);
        if (Character.isDigit(a)) {
            number = number + a;
            //numbersList.add("" + a);
        } else {
            letter = letter + a;
            stringList.add("" + a);
        }
    }

    Matcher m = Pattern.compile("\\d+").matcher(str);
      //List<Integer> numbers = new ArrayList<Integer>();
      while(m.find()) {
        numbersList.add(""+Integer.parseInt(m.group()));
      }
     // System.out.println(numbers);

    for (int i = 0; i < stringList.size(); i++) {

        int j = Integer.parseInt(numbersList.get(i));
        String concatStr = stringList.get(i);

        int count = 0;
        for (int k = 1; k <= j; k++) {
            concatStr = concatStr + concatStr;
            if (k == j)
                count = k;
        }
        resStr = resStr + concatStr.substring(0, count);

        concatStr = "";

    }

    return resStr;
}

}