我想将 String
中的字母乘以数字并返回其他String
。
我不知道当数字大于9时如何连接然后相乘
例如。
String ="a2b10"
转换为 String ="aabbbbbbbbbb"
字符串可以有不同的值:"a2b15"
、"a16b4c1"
、"a11b14c5"
下面我只制作了一个字母和一个数字,例如。 a1b8
,a4b7v3
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/