2017-08-06 37 views
3

我想從原始文件中讀取數據並替換文本中的格式。如何從原始文件讀取並在String.format中使用

比如...在一個原始文件是這樣的:

hello {0}, my name id {1}, my age is {2}.... 

當我使用的String.format,如下圖所示,文字失去了它的縮進。

String data = readTextFile(this, R.raw.input); 
data = String.format(data, "world", "josh", "3"); 

有沒有人知道如何做到這一點,而不會失去縮進?

+0

月1日,我認爲這'{0} {1} ...'將無法正常工作,Java使用'% d'代表數字,'%s'代表字符串,第二,你們通過'文本失去縮進'是什麼?你能發佈預期產出和實際產出嗎? – Yazan

+0

你爲什麼要使用文件? https://stackoverflow.com/a/20887690/2308683 –

+0

因爲我有一個大文本... – chaim

回答

0

我發現我的問題的解決方案。

有一個在一個多變量需要,這是不可能分配到相同的變量

String data = readTextFile(this, R.raw.input); 
String output = String.format(data, "world", "josh", "3"); 
1

您提供的代碼看起來更像String.format,例如從C#。在Java中的String.format不能以這種方式工作,它更像printf。

你可以操縱你的輸入看起來像這樣。

String input = "hello %s, my name id %s, my age is %s"; 
String.format(input, "world", "josh", "3"); 

輸出: hello world, my name id josh, my age is 3

縮進應該是相同的

編輯

如果你想用括號您可以使用MessageFormat.format代替String.format

String messageInput = "hello {0}, my name id {1}, my age is {2}"; 
MessageFormat.format(messageInput,"world", "josh", "3"); 
+0

其實Java支持... https://stackoverflow.com/questions/5324007/java-equivalent-of-蟒蛇格式 –

+0

對,很好提及一個'MessageFormat' – robinloop

+0

是否有可能在括號中使用多次, 我的意思是: String messageInput =「你好{0},我的名字是{1},我的年齡是{0}「; MessageFormat.format(messageInput,「world」,「josh」); – chaim

0

可以使用Regular Explessions與模式類似:"{/d++}"

String format (String input, String... args) { 
    Pattern p = Pattern.compile("{/d++}"); 
    String[] parts = p.split(input); 
    StringBuilder builder = new StringBuilder(""); 
    int limit = Math.min(args.length, parts.length); 
    for(int i = 0; i < limit; i++){ 
     builder.append(parts[i]).append(args[i]); 
    } 
    return builder.toString(); 
} 
相關問題