正则表达式实际上可能比显式解析您需要的内容慢。所需的表达式可能也有点复杂。这是不需要大型数组的替代方案:
String input = "{a},{b2},{str},{5}";
int insertPos = 3;
String insertText = "{c3}";
StringBuilder sb = new StringBuilder();
int pos = 0;
Scanner scanner = new Scanner(input).useDelimiter(",");
while (scanner.hasNext()) {
String next = scanner.next();
if (pos++ == insertPos) {
sb.append(insertText);
sb.append(',');
}
sb.append(next);
sb.append(',');
}
sb.deleteCharAt(sb.length() - 1); // remove the last comma
String output = sb.toString(); // output will be "{a},{b2},{str},{c3},{5}"
我不确定您的用例是什么,但是您可以根据需要进行调整以处理更多插入。
Edit:这是一个速度快 50 倍的版本。给定每个具有 50K 索引的字符串,在典型硬件上,它可以在单个线程中每分钟处理大约 100K 输入字符串(因此每分钟 50 亿个索引)。
String input = "{a},{b2},{str},{5}";
int insertPos = 3;
String insertText = "{c3}";
String output = input + ","; // add temporary comma
int index = 0;
int pos = 0;
while (index > -1) {
if (pos == insertPos) {
output = output.substring(0, index)
+ (pos == 0 ? insertText + "," : "," + insertText)
+ output.substring(index);
}
index = output.indexOf(',', index + 1);
pos++;
}
output = output.substring(0, output.length() - 1); // remove last comma
System.out.println(output); // output will be "{a},{b2},{str},{c3},{5}"