提出这个问题非常困难,我确信它仍然不清楚。
我有一个 CSV 文件,例如:名字;姓氏;地址;产品 1;产品 2;产品 3;产品 4;
我想开始替换“;”和 ”::”。问题是,我想在第三个分号之后开始替换。
我知道这可以在 while 循环中完成,我检查每个字符,当出现分号时我将计数 +1,如果计数器为 3,我将开始替换。但是有没有一种方法可以在没有循环的情况下做到这一点?
最佳答案
您可以使用indexOf(char,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
输入控制和性能较差,但我们没有任何循环:)
关于java - 如何在某个时刻开始替换字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25644136/