gpt4 book ai didi

java - 一次替换所有出现的子字符串

转载 作者:行者123 更新时间:2023-12-01 17:53:38 24 4
gpt4 key购买 nike

我有以下方法来替换所有出现的 {TIMESTAMP} String.valueOf(System.nanoTime()) 返回值的子字符串,目的是为每个子字符串出现获取不同的时间标记,但这会导致所有子字符串都被相同的值替换。

class StringUtils {
private static String resolveTimestamp(String s) {
String timestamp = "\\{TIMESTAMP}";
return s.replaceAll(timestamp, String.valueOf(System.currentTimeMillis()));
}
}

class Sample {
public static void main(String[] args) {
StringUtils.resolveTimestamp("{TIMESTAMP}, {TIMESTAMP}, {TIMESTAMP}")
}
}

// The execution of the code above would result in:
// 241170886964203, 241170886964203, 241170886964203

// But I want to get this:
// 241733154573329, 241734822930540, 241751957270934

我想知道哪种方法是做我想做的事情的最佳方法,因为我现在想到了几种方法:

  • 带有 s.matches(timestamp) 的循环作为迭代子字符串每次出现的条件,并且 s.replaceFirst(timestamp, String.valueOf(System.nanoTime()))在循环内执行替换。
  • 使用子字符串将字符串分解为多个 block s.split(timestamp) ,并迭代连接每对的 block 与 String.valueOf(System.nanoTime())) 返回的值
  • 可能还有其他选择

注意:请注意,这与 in this question 所解决的问题不同。 。他们需要用相同的值替换多次出现的固定模式,而我需要替换多次出现的相同子字符串,每个子字符串都替换为运行时计算的不同值。

最佳答案

您可以使用 String.replaceFirst:

private static String resolveTimestamp(String s) {
String timestamp = "\\{TIMESTAMP}";

while(s.matches(timestamp)) {
s = s.replaceFirst(timestamp, String.valueOf(System.nanoTime()));
}
return s;
}

关于java - 一次替换所有出现的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47356305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com