java - 解析/转换包含字符和数字的任务
问题描述
有必要重复该字符,其次数与其后面的数字一样多。
它们是正整数。
case #1
input: "abc3leson11"
output: "abccclesonnnnnnnnnnn"
我已经通过以下方式完成了它:
String a = "abbc2kd3ijkl40ggg2H5uu";
String s = a + "*";
String numS = "";
int cnt = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) {
numS = numS + ch;
cnt++;
} else {
cnt++;
try {
for (int j = 0; j < Integer.parseInt(numS); j++) {
System.out.print(s.charAt(i - cnt));
}
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
} catch (Exception e) {
if (i != s.length() - 1 && !Character.isDigit(s.charAt(i + 1))) {
System.out.print(s.charAt(i));
}
}
cnt = 0;
numS = "";
}
}
但我想知道有没有更好的解决方案,代码更少更干净?
解决方案
你能看看下面吗?我正在使用StringUtils
来自Apache Common Utils的库来重复字符:
public class MicsTest {
public static void main(String[] args) {
String input = "abc3leson11";
String output = input;
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(input);
while (m.find()) {
int number = Integer.valueOf(m.group());
char repeatedChar = input.charAt(m.start()-1);
output = output.replaceFirst(m.group(), StringUtils.repeat(repeatedChar, number));
}
System.out.println(output);
}
}
如果您不想使用StringUtils
. 您可以使用以下自定义方法来达到相同的效果:
public static String repeat(char c, int times) {
char[] chars = new char[times];
Arrays.fill(chars, c);
return new String(chars);
}
推荐阅读
- firebase - 我想将我的电子商务应用的购物车详细信息保存到本地存储中
- java - 有没有办法返回调用者不可见的 API 调用元素?
- javascript - 有return语句并且什么都不返回
- sql - 如何从 WHERE 子句引用的表中获取行数据
- javascript - 我如何添加关闭按钮并调整 jQuery 模式的大小
- amazon-web-services - 我无法在 AWS EC2 上安装 PHP
- java - 如何在 Eclipse 中运行 Alloy 模型检查器 API?
- python - distutils.spawn 不可用,除非导入
- javascript - 如何在javascript中找到二维对象数组的索引
- javascript - 缓冲区溢出 - ZAP 扫描报告 - 打字稿文件中的节点 JS 微服务