2017-03-02 91 views
1

取代圖案我有字符串的陣列,其看起來像這樣: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)); 
+1

如果明星都只是出現在年底你'line',你可以計算它們的數量:'int starIndex = line.indexOf(「*」); int numberOfStars = line.length() - line.substring(starIndex).length();'indexOf(String str)'方法返回字符串中第一次出現的字符/字符串。 – peech

回答

0

我試試這個:

String test = "test****"; //test: "test****" 
int one = test.indexOf("*"); //one: 4 
int two = test.lastIndexOf("*"); //two: 7 
int nb = two-one; //nb: 3 two: 7 one: 4 

String newTest= test.replace("*","0"); //newTest: "test0000" 
String step = "12"; //step: "12" 
newTest = newTest.substring(0,newTest.length()-step.length()); //newTest: "test00" 
newTest += step; //newTest: "test001" 

你還可以在'nb'和'step.length()'之間添加大小檢查。如果step.length()比你的數字或'*'更高,你會怎麼做?

1

首先嚐試預先用'0'填充字符串,在末尾添加您的幻數。然後,只要substring會起作用,因爲你知道'*'有多長以及它們從哪裏開始。

這也適用於:

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); 
0

我寫此代碼爲您的問題:

int step = 94; 
    String[] input = new String[]{ 
     "someThing/one_text_0000_temperature****", 
     "another/two_text_0000_temperature****", 
     "where/three_text_0000_temperature****" 
    }; 

    for (String i : input) { 
     int start = i.indexOf('*'); 
     int size = i.length() - start; 
     int stepsize = (step + "").length(); 
     if(stepsize > size) { 
      throw new IllegalArgumentException("Too big step :D"); 
     } 
     String result = i.replace('*', '0').substring(0, i.length() - stepsize) + step; 

     System.out.println(result); 
    } 

我希望這可以幫助您:)