我有一个字符串数组,如下所示:
someThing/one_text_0000_temperature****
another/two_text_0000_temperature****
where/three_text_0000_temperature****
我有可变步长。
int step
我需要用可变步骤中的数字替换那些****。
步长为 94 时的输出示例:
someThing/one_text_0000_temperature0094
another/two_text_0000_temperature0094
where/three_text_0000_temperature0094
问题是 * 的数量正在变化。嗯,当程序运行时,每个字符串都是恒定且相同的。但这些字符串来自文件。下次启动程序时*的数量可能会不同,文件已更改。
我想我会分三步完成:找到星星的数量,格式化字符串,最后用新字符串替换部分字符串
问题1) 如何找出星星的数量?
问题2) 如何将步骤变量格式化为动态长度字符串?不是这样的:
String.format("%04d", step); // how to change that 4 if needed?
问题3)
如何用另一个字符串替换部分字符串
这可以通过调用替换来完成。不确定 line = line.replace( ) 是否有效/正确?
String line = new String("someThing/one_text_0000_temperature****");
String stars = new String("****"); // as result of step 1
String stepString = new String("0094"); // as result of step 2
line = line.replace(stars, stepString);
非常感谢您的提示/帮助
已编辑
谢谢你的灵感。我确实在这里找到了更多想法Simple way to repeat a String in java和我的最终代码:
int kolko = line.length() - line.indexOf("*");
String stars = String.format("%0"+kolko+"d", 0).replace("0", "*");
String stepString = String.format("%0"+kolko+"d", step);
我在 HashMap 中存储了行,因此我可以使用 lambda
lines.replaceAll((k, v) -> v.replace(stars, stepString));
最佳答案
首先尝试用“0”预填充字符串,然后在末尾添加您的魔数(Magic Number)。然后简单的子字符串就可以工作,因为您知道“*”有多长以及它们从哪里开始。
这也有效:
String s1 = "someThing/one_text_0000_temperature****";
String step = "94";
String v = "0000000000" + step;
String result = s1.substring(0, s1.indexOf('*')) + v.substring(v.length() - s1.length() - s1.indexOf('*'));
System.out.println(result);
关于java - 字符串 : replace pattern with formatted number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42559305/