用模式对Java字符串数组进行排序

huangapple 未分类评论44阅读模式
英文:

Sorting a Java String Array with a pattern

问题

我目前正在读写一个文本文件,但无法弄清楚如何进行排序。我原以为可以按模式进行排序。我想按照模式(0-9、A-Z、a-z)对Java字符串数组进行排序。基本上,我想忽略非字母数字字符,按数字排在字母前面,大写字母排在小写字母前面(即,0-9、A-Z、a-z)。我想要删除只包含非字母数字字符的行。

File f1 = new File(fp);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
    count++;
    // 排序部分放在这里

    if (line.contains(sx)) {
        line = line.replace(line, "");
    }

    if (yint > 0 && !line.isBlank()) {
        line = line.substring(yint);
    }

    if(!line.isBlank()){
        line = line.replace(line, count + " " + line + "\n");
        lines.add(line);
    } else {
        lines.add(line);
    }
}
fr.close();
br.close();

FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
    out.write(s);
out.flush();
out.close();
英文:

I am currently reading and writing to a text file and I cant figure out a way to sort. I thought I would be able to sort by pattern. I would like to sort a java string array by the pattern (0-9, A-Z, a-z). Basically I would like to ignore non-alphanumeric characters, sort with numbers preceding letters, and capital letters preceding lowercase letters (i.e., 0-9, A-Z, a-z). I would like to remove lines that only have non-alphanumeric characters.

File f1 = new File(fp);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
List&lt;String&gt; lines = new ArrayList&lt;String&gt;();
String line;
while ((line = br.readLine()) != null) {
    count++;
    // SORT GOES HERE

    if (line.contains(sx)) {
        line = line.replace(line, &quot;&quot;);
    }

    if (yint &gt; 0 &amp;&amp; !line.isBlank()) {
        line = line.substring(yint);
    }

    if(!line.isBlank()){
        line = line.replace(line, count + &quot; &quot; + line + &quot;\n&quot;);
        lines.add(line);
    } else {
        lines.add(line);
    }
}
fr.close();
br.close();

FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
    out.write(s);
out.flush();
out.close();

答案1

得分: 0

我可能会在最后使用类似Collections.sort()的东西,以及在循环中进行简单的检查:

File f1 = new File(fp);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
    count++;

    if (!line.matches("[a-zA-Z0-9]+")) {
        continue;
    }

    if (line.contains(sx)) {
        line = line.replace(line, "");
    }

    if (yint > 0 && !line.isBlank()) {
        line = line.substring(yint);
    }

    if (!line.isBlank()) {
        line = line.replace(line, count + " " + line + "\n");
        lines.add(line);
    } else {
        lines.add(line);
    }
}
fr.close();
br.close();

Collections.sort(lines, (a, b) -> {
    String aNum = a.replaceAll("[^a-zA-Z0-9]", "");
    String bNum = b.replaceAll("[^a-zA-Z0-9]", "");
    return a.compareTo(b);
});

FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for (String s : lines)
    out.write(s);
out.flush();
out.close();

编辑:你当然可以通过在排序等地方进行快速检查来使其更快/更好 - 但总的来说,我认为这就是这个想法。

英文:

I would likely use something like Collections.sort() at the end and a simple check in the loop:

    File f1 = new File(fp);
    FileReader fr = new FileReader(f1);
    BufferedReader br = new BufferedReader(fr);
    List&lt;String&gt; lines = new ArrayList&lt;String&gt;();
    String line;
    while ((line = br.readLine()) != null) {
        count++;

        if (!line.matches(&quot;[a-zA-Z0-9]+&quot;)) {
            continue;
        }

        if (line.contains(sx)) {
            line = line.replace(line, &quot;&quot;);
        }

        if (yint &gt; 0 &amp;&amp; !line.isBlank()) {
            line = line.substring(yint);
        }

        if(!line.isBlank()){
            line = line.replace(line, count + &quot; &quot; + line + &quot;\n&quot;);
            lines.add(line);
        } else {
            lines.add(line);
        }
    }
    fr.close();
    br.close();

    Collections.sort(lines, (a, b) -&gt; {
        String aNum = a.replaceAll(&quot;[^a-zA-Z0-9]&quot;, &quot;&quot;);
        String bNum = b.replaceAll(&quot;[^a-zA-Z0-9]&quot;, &quot;&quot;);
        return a.compareTo(b);
    });

    FileWriter fw = new FileWriter(f1);
    BufferedWriter out = new BufferedWriter(fw);
    for(String s : lines)
        out.write(s);
    out.flush();
    out.close();

EDIT: You can certainly make this work faster/better by quick-checking perhaps in the sort, etc - but generally this is the idea I think

答案2

得分: 0

在读取文件时无法对其进行排序在您的情况下需要在进行以下操作之前对文件进行排序

	// 对文件进行排序
    Path initialFile = Paths.get("myFile.txt");
	List<String> sortedLines = Files.lines(initialFile)
			.sorted()
			.collect(Collectors.toList());
	
    // 处理已排序的行
	List<String> lines = new ArrayList<String>();
	int count = 0;
	for (String line : sortedLines) {
		System.out.println("l: " + line);
		count++;

		if (line.contains(sx)) {
			line = line.replace(line, "");
		}

		if (yint > 0 && !line.isEmpty()) {
			line = line.substring(yint);
		}

		if (!line.isEmpty()) {
			System.out.println("line: " + line);
			line = line.replace(line, count + " " + line + "\n");
			System.out.println("new line: " + line);
			lines.add(line);
		} else {
			System.out.println("add: " + line);
			lines.add(line);
		}
	}
	// 写入输出文件
	File f1 = new File("myFile.txt");
	try (BufferedWriter out = new BufferedWriter(new FileWriter(f1))) {
		for (String s : lines)
			out.write(s);
	}
英文:

You can't sort the file while you are reading it, in your case it needs to be done before:

// Sort the file
Path initialFile = Paths.get(&quot;myFile.txt&quot;);
List&lt;String&gt; sortedLines = Files.lines(initialFile)
		.sorted()
		.collect(Collectors.toList());

// Process the sorted lines
List&lt;String&gt; lines = new ArrayList&lt;String&gt;();
int count=0;
for(String line : sortedLines) {
	System.out.println(&quot;l: &quot;+line);
	count++;

	if (line.contains(sx)) {
		line = line.replace(line, &quot;&quot;);
	}

	if (yint &gt; 0 &amp;&amp; !line.isEmpty()) {
		line = line.substring(yint);
	}

	if (!line.isEmpty()) {
		System.out.println(&quot;line:&quot;+line);
		line = line.replace(line, count + &quot; &quot; + line + &quot;\n&quot;);
		System.out.println(&quot;new line:&quot;+line);
		lines.add(line);
	} else {
		System.out.println(&quot;add:&quot;+line);
		lines.add(line);
	}
}
// Write output file
File f1 = new File(&quot;myFile.txt&quot;);
try(BufferedWriter out = new BufferedWriter( new FileWriter(f1))){
	for (String s : lines)
		out.write(s);
}

答案3

得分: 0

static void sortByAlphaNumeric(String inFile, String outFile) throws IOException {
List lines = Files.readAllLines(Paths.get(inFile)).stream()
.map(line -> new Object() {
String sortKey = line.replaceAll("[^0-9A-Za-z]", "");
String originalLine = line;
})
.filter(obj -> !obj.sortKey.equals(""))
.sorted(Comparator.comparing(obj -> obj.sortKey))
.map(obj -> obj.originalLine)
.collect(Collectors.toList());
Files.write(Paths.get(outFile), lines);
}

英文:

Try this.

static void sortByAlphaNumeric(String inFile, String outFile) throws IOException {
    List&lt;String&gt; lines = Files.readAllLines(Paths.get(inFile)).stream()
        .map(line -&gt; new Object() {
            String sortKey = line.replaceAll(&quot;[^0-9A-Za-z]&quot;, &quot;&quot;);
            String originalLine = line;
        })
        .filter(obj -&gt; !obj.sortKey.equals(&quot;&quot;))
        .sorted(Comparator.comparing(obj -&gt; obj.sortKey))
        .map(obj -&gt; obj.originalLine)
        .collect(Collectors.toList());
    Files.write(Paths.get(outFile), lines);
}

huangapple
  • 本文由 发表于 2020年7月27日 11:02:09
  • 转载请务必保留本文链接:https://java.coder-hub.com/63108112.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定