我有以下字符串数组:
February_Report_files\customerst.rptdesign
February_Report_files\Top10Percent.rptdesign
February_Report_files\TopNPercent.rptdesign
March_Report_files\by_sup_ML.rptdesign
March_Report_files\chart__cwong.rptdesign
March_Report_files\HTML5 Chart.rptdesign
我希望根据不同的文件夹名称将报告文件(* .rptdesign)文件保存在不同的字符串数组中。例如:
result[0]="customerst.rptdesign,Top10Percent.rptdesign,TopNPercent.rptdesign"
result[1]="by_sup_ML.rptdesign,chart__cwong.rptdesign,HTML5 Chart.rptdesign"
我怎样才能得到这个结果?你能给我一些建议吗?
答案 0 :(得分:1)
以下是快速代码段:
public static void main (String[] args)
{
/* Sample Space */
String[] strArr = new String[] {
"February_Report_files\\customerst.rptdesign",
"February_Report_files\\Top10Percent.rptdesign",
"February_Report_files\\TopNPercent.rptdesign",
"March_Report_files\\by_sup_ML.rptdesign",
"March_Report_files\\chart__cwong.rptdesign",
"March_Report_files\\HTML5 Chart.rptdesign",
};
/* Sort Sample Space */
Arrays.sort(strArr);
/* Initialize Result ArrayList */
List<String> resultList = new ArrayList<>();
/* Initialize */
String[] strInit = strArr[0].split("\\\\");
String prefix = strInit[0];
StringBuilder result = new StringBuilder(strInit[1]);
for(int i = 1; i < strArr.length; i++) {
/* Split Using Backslash */
String[] strSplit = strArr[i].split("\\\\");
if(strSplit[0].equals(prefix)) {
/* Append */
result.append("," + strSplit[1]);
} else {
/* Add Result To List */
resultList.add(result.toString());
/* Reset Prefix, Result Strings */
prefix = strSplit[0];
result = new StringBuilder(strSplit[1]);
}
}
/* Add Last Entry To List */
resultList.add(result.toString());
/* Print The Results */
for(int i = 0; i < resultList.size(); i++) {
System.out.println(resultList.get(i));
}
}
该计划的输出:
customerst.rptdesign,Top10Percent.rptdesign,TopNPercent.rptdesign
by_sup_ML.rptdesign,chart__cwong.rptdesign,HTML5 Chart.rptdesign
答案 1 :(得分:1)
以下是使用hashmap的实现
for(int i=0;i<strarr.length;i++){
boolean blnExists=false;
String key = strarr[i].substring(0,strarr[i].indexOf("\\"));
String value=strarr[i].substring(strarr[i].indexOf("\\")+1);
blnExists = result.containsKey(key);
if(blnExists){
value=result.get(key) + ","+value;
}
else{
result.put(key, value);
}
result.put(key, value);
}
`
答案 2 :(得分:0)
使用startsWith()
:
if(fileName[i].startsWith("March_Report_files"))
saveItHere(fileName[i]);
else
saveItThere(fileName[i]);
您可能希望以后使用
缩短字符串fileName[i]=fileName[i].replaceFirst.("March_Report_files","");
例如:
public class StringTest {
public static void main(String[] args){
String text = "Hello\\World";
if(text.startsWith("Hello\\"))
text=text.replaceFirst("Hello\\\\","");
System.out.println(text);
}
}