将字符乘以字符串中的数字

时间:2016-12-15 21:19:01

标签: java

我想在String中将数字乘以数字并返回其他String。 当数字高于9然后相乘时,我不知道如何连接它 例如。

String ="a2b10"转换为String ="aabbbbbbbbbb"

字符串可以包含不同的值:"a2b15""a16b4c1""a11b14c5"

下面我只用了一个字母和一个数字,例如。 a1b8a4b7v3

import javafx.util.converter.CharacterStringConverter;

public class Test {

public static void main(String[] args) {
    String txt = "a3b2";
    char ch;

    for (int i = 0; i < txt.length(); i++) {
        ch = txt.charAt(i);

        if (((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) {

        } else if (ch >= '0' && ch <= '9')

        {

            int count = Character.getNumericValue(ch);
            for (int j = 0; j < count; j++) {
                System.out.print(txt.charAt(i - 1));

            }

        } else
            System.out.println("not a letter");

    }
}

}

3 个答案:

答案 0 :(得分:2)

在这种情况下,使用正则表达式和组匹配更容易提取字母及其后面的数字:

while (!($handle = fopen("https://www.fmasarovic.com/export_feed.php?preset=poshbag_boutique", "r"))) {
    sleep(1); // So we don't hammer the website continuously
}
while ($row = fgetcsv($handle)) {
    $csv[] = $row;
}

<强>输出

public static void main(String[] args) {
    String txt = "a3b10";
    String patt = "([a-z])([0-9]*)"; // ([a-z]) will be the first group and ([0-9]*) will be the second

    Pattern pattern = Pattern.compile(patt);
    Matcher matcher = pattern.matcher(txt);

    while(matcher.find()) {
        String letter = matcher.group(1);
        String number =  matcher.group(2);
        int num = Integer.valueOf(number);
        while (num > 0) {
            System.out.print(letter);
            num--;
        }
    }
}

答案 1 :(得分:0)

当你正在寻找数字并找到数字时,请继续寻找数字,直到找到一个字母或字符串的结尾。

答案 2 :(得分:0)

你可以这样做......

public class Test {

public static void main(String[] args) {
    String txt = "a10b10";
    char ch;
    char tempChar = ' ';
    int temp = -1;
    for (int i = 0; i < txt.length(); i++) {
        ch = txt.charAt(i);

        if (((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) {
            temp = -1;
            tempChar = ch;
        } else if (ch >= '0' && ch <= '9') {

            int count = Character.getNumericValue(ch);

            if (temp != -1) {
                count = ((10*temp) - temp);
            }

            for (int j = 0; j < count; j++) {
                //System.out.print(txt.charAt(i - 1));
                System.out.print(tempChar);

            }
            temp = count;

        } else {
            System.out.println("not a letter");
        }

    }

}

}