繁体   English   中英

用中间的数字分割字符串

[英]Splitting a String by the numbers in between

我试图在数字拆分字符串。 例如,如果我有

字符串x = 2A2B;

我希望能够将字符串拆分为多个部分,然后在屏幕上打印出“ AABB”。 有人可以帮我吗?

下面的代码段可能会帮助您

    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();

    }

尝试使用java.util.Scanner

Scanner.nextInt()
Scanner.next()

他们将帮助您完成任务。

它可以满足您的基本目的:

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

我建议为此使用扫描仪+分隔符。

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

将读取字符串,并用数字(\\ d)分割,然后next()应该首先给出“ A”,然后给出“ B”

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

将读取字符串,除以数字的任何内容,next()应该返回“ 2”,然后返回“ 2”

像这样的东西? (假设总有一个数字后跟一个字母)

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