2014-09-03 23 views
0

這個問題很難形成,我相信它仍然不清楚。如何開始替換角色?

我有一個CSV文件例如:名字;姓氏;地址;產品1;產品2;產品3;產品4;

我想開始替換「;」與「::」。問題是,我想在第三個分號後開始替換。

我知道它可以在while循環中完成,我檢查每個字符,當發生分號時我會計數+1,如果計數器是3,我將開始替換。但是沒有一種方式沒有循環如何去做?

回答

2

可以使用的indexOf(焦炭,fromIndex)個方法。 你的第三個分號位置搜索可內聯:

csvLine.indexOf(';', csvLine.indexOf(';', csvLine.indexOf(';') + 1) + 1) 


我們假設我們csvLine有至少3個分號...

String csvLine = "Firstname;Lastname;Adress;product1;product2;product3;product4"; 

    //Index of "fromIndex" param is inclusive, that's why we need to add 1 
    int pos = csvLine.indexOf(';', csvLine.indexOf(';', csvLine.indexOf(';') + 1) + 1); 

    //Retrieve string from the char after the third semi-colon 
    String truncatedLine = csvLine.substring(pos + 1); 

    //Replace ";" by "::" on our substring 
    truncatedLine = truncatedLine.replaceAll(";", "::"); 

    //Then concat the first part of csvLine with the second 
    String result = csvLine.substring(0, pos + 1).concat(truncatedLine); 

    System.out.println(result); //Print => Firstname;Lastname;Adress;product1::product2::product3::product4 

差輸入控制和性能,但我們不這樣做有任何循環:)

0

如果我明白你想要什麼,試試這個。第三分號 首先搜索SE位置:

String csvContent = "Firstname;Lastname;Adress;product1;product2;product3;product4;"; 
int i = 0; 
int index= 0; 
while(i < 4){ 
    index = csvContent.indexOf(';', (index + 1)); 
    i++; 
}//index = position of the thrid semicolon 

其次,切斷索引位置您的CSV內容。

String tmp1 = csvContent.substring(0, index); 
String tmp2 = csvContent.substring(index, csvContent.length()); 

第三,全部替換';'通過 '::':

tmp2 = tmp2.replaceAll(";", "::"); 

Finaly,重建文件內容:

csvContent = tmp1 + tmp2; 
0
int i = 0; 
int pos = 0; 
while (i < 3) { 
    pos = string.indexOf(';', pos+1); 
    i++; 
} 
String newString = string.substring(0, pos) +";"+ (string.substring(pos + 1, string.length()).replace(";", "::")); 
0

如何正則表達式的解決方案?

Pattern pattern = Pattern.compile("(.*?;.*?;.*?;)(.*)"); 
Matcher match = pattern.matcher(str); 

if(match.matches()) { 
    String firstThree = match.group(1); 
    String rest = match.group(2); 
    rest = rest.replace(";", "::"); 
    return firstThree + rest; 
}