我正在尝试删除字符串中的每个数字,然后复制该数字后面的字母。
例如,字符串4a2b
应输出aaaabb
。
到目前为止,我的代码看起来像这样:
Scanner scan= new Scanner(System.in);
String s = scan.nextLine();
String newString = s.replace(" ", "");
newString=newString.replaceAll("\\W+", "");
newString=newString.replaceAll("\\d+", "");
System.out.println(newString);
是否可以使用正则表达式和replaceAll来做到这一点?
答案 0 :(得分:0)
尝试,
String newString = "4a2b";
String num = "";
StringBuilder res = new StringBuilder();
for (int i = 0; i < newString.length(); i++) {
char ch = newString.charAt(i);
if (Character.isDigit(ch)) {
num += ch;
} else if (Character.isLetter(ch)) {
if (num.length() > 0) {
for (int j = 0; j < Integer.parseInt(num); j++) {
res.append(ch);
}
}
num="";
}
}
System.out.println(res);
答案 1 :(得分:0)
试试这个:
public static void main(String[] args)
{
String str = "ae4a2bca";
Matcher m = Pattern.compile("(\\d+)(.)").matcher(str);
StringBuffer sb = new StringBuffer();
while (m.find())
{
m.appendReplacement(sb, times("$2", Integer.parseInt(m.group(1))));
}
m.appendTail(sb);
System.out.println(sb.toString());
}
private static String times(String string, int t)
{
String str = "";
for (int i = 0; i < t; ++i) str += string;
return str;
}