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

标签 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");

    }
}

}

最佳答案

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

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

输出

aaabbbbbbbbbb

关于java - 将字符串中的字符乘以数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41173494/

相关文章:

java 1.5 : Best practice to keep constants for column name of db tables?

java - 使用扫描仪扫描包含空格的文本时会跳过输入

java - 如何加载集成测试数据

java - SOLR选择请求错误-Java类转换异常

Java + Django 网络服务?

java - 代码中是否发生了线程饥饿死锁?

java - Tomcat 8.5 上的 Ant 重新部署失败 - 在流模式下出现 java.net.HttpRetryException : cannot retry due to server authentication,

java - 从链接对象模型创建表

java - 使用 iText 在网络浏览器中显示 PDF 文件

java - 无法捆绑适用于 Mac 的 Java 应用程序 1.8