取代圖案我有字符串的陣列,其看起來像這樣:STRING:與格式化的數
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
問題是*的該數目是變化。那麼,當程序運行時,它對每個字符串都是一樣的。但是這些字符串來自文件。在程序的下一個開始*號可以不同,文件已經改變。
我想,我會做,在3個步驟:找到星號,格式一步轉換爲字符串,並finaly用新的字符串替換字符串的一部分
問題1) 如何找出數星星?
問題2) 如何將step變量格式化爲動態長度字符串?不喜歡這樣的:
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的線,所以我可以用拉姆達
lines.replaceAll((k, v) -> v.replace(stars, stepString));
如果明星都只是出現在年底你'line',你可以計算它們的數量:'int starIndex = line.indexOf(「*」); int numberOfStars = line.length() - line.substring(starIndex).length();'indexOf(String str)'方法返回字符串中第一次出現的字符/字符串。 – peech