简体   繁体   中英

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;

I want to be able to be able to split the String into parts and then print out "AABB" to the screen. 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

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"

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"

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]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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