java - java中如何比较字符串并将结果保存到字符串数组中?

标签 java arrays 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

我想根据不同的文件夹名称将报告文件(*.rptdesign)文件保存在不同的字符串数组中。例如:

result[0]="customerst.rptdesign,Top10Percent.rptdesign,TopNPercent.rptdesign"

 result[1]="by_sup_ML.rptdesign,chart__cwong.rptdesign,HTML5 Chart.rptdesign"

我怎样才能得到这个结果?你能给我一些建议吗?

最佳答案

这是一个快速代码片段:

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

关于java - java中如何比较字符串并将结果保存到字符串数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35151643/

相关文章:

c# - 如何将 SQL 结果放入 STRING 变量中?

Java - 具有显示箭头的按钮

java - Lucene Porter Stemmer 线程安全吗?

java - 如何在 Android 应用程序中读取 xlsx 文件?

c++ - 如何销毁一个数组

python - 如何将带分隔符的字符串拆分成一个集合?

java - TreeMap 通用参数警告

php - php array_unique 的奇怪行为

javascript - 获取数组中出现次数最多的项

c - 即使数组不为空,数组大小也为零