简体   繁体   English

用中间的数字分割字符串

[英]Splitting a String by the numbers in between

I'm trying to split a String at the numbers. 我试图在数字拆分字符串。 For example if I have 例如,如果我有

String x = 2A2B; 字符串x = 2A2B;

I want to be able to be able to split the String into parts and then print out "AABB" to the screen. 我希望能够将字符串拆分为多个部分,然后在屏幕上打印出“ AABB”。 Can anyone help me with that? 有人可以帮我吗?

Below code snippet may help you 下面的代码段可能会帮助您

    String str = "3A2B";
    // split the string on
    String st[] = str.split("(?<=\\D)(?=\\d)");
    System.out.println(Arrays.toString(st));
    for (String s : st) {
        String intValue = s.substring(0, s.length()-1);
        int i = Integer.parseInt(intValue);
        char c = s.charAt(s.length()-1);
        while (i > 0) {
            System.out.print(c);
            i--;
        }
        System.out.println();

    }

Try using a java.util.Scanner 尝试使用java.util.Scanner

Scanner.nextInt()
Scanner.next()

They will help you with your task. 他们将帮助您完成任务。

It can server your basic purpose: 它可以满足您的基本目的:

String x = "2A2B";
int times = 0;
for(char ch:x.toCharArray()){
    if(Character.isDigit(ch)){
        times = times*10+(Integer.valueOf(String.valueOf(ch)));
    }else{
        do{
            System.out.print(ch);
            times--;
        }while(times > 0);
        times = 0;
    }
}

I would suggest using scanners + delimiters for this. 我建议为此使用扫描仪+分隔符。

Scanner s = new Scanner(input).useDelimiter("\d");

Will read the string, splitting it by digits (\\d), and next() should first give "A", then "B" 将读取字符串,并用数字(\\ d)分割,然后next()应该首先给出“ A”,然后给出“ B”

Scanner s = new Scanner(input).useDelimiter("\D");

Will read the string, splitting by anything that's not a digit, next() should return "2", then "2" 将读取字符串,除以数字的任何内容,next()应该返回“ 2”,然后返回“ 2”

Something like this maybe? 像这样的东西? (assuming there's always one number followed by one letter) (假设总有一个数字后跟一个字母)

String rawSequence = "2U2D1L1R1L1R1B1A";
string newSequence = "";

Scanner scanLetters = new Scanner(rawSequence);
scanLetters.useDelimiter("\d");
Scanner scanNumbers = new Scanner(rawSequence);
scanLetter.useDelimeter("\D");

String[] letters = new String[ rawSequence.length()/2 ];
int[] amounts = new int[ rawSequence.length()/2 ];

for (int x = 0; x < rawSequence.length(); x++){
    letters[x] = scanLetters.next()
    numbers[x] = scanNumbers.next()
}

for (int i = 0, i < amounts.length, i++){
    for (int j = 0; j < amounts[i], j++){
        newSequence.concat(letters[i]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM