我的字符串是:
"EEE
EEE
AAA
BBB
CCC
BBB
DDD
CCC"
但我需要没有相同的行这个字符串。 像这样:
"EEE
AAA
BBB
CCC
DDD"
我该怎么做?
答案 0 :(得分:1)
考虑到您将字符串存储在String s
中,
String[] tokens = s.split("\n");
StringBuilder resultBuilder = new StringBuilder();
Set<String> alreadyPresent = new HashSet<String>();
boolean first = true;
for(String token : tokens) {
if(!alreadyPresent.contains(token)) {
if(first) first = false;
else resultBuilder.append("\n");
if(!alreadyPresent.contains(token))
resultBuilder.append(token);
}
alreadyPresent.add(token);
}
String result = resultBuilder.toString();
或:
Set<String> tokens = new HashSet<String>(Arrays.asList(s.split("\n")));
StringBuilder resultBuilder = new StringBuilder();
boolean first = true;
for(String token : tokens) {
if(first) first = false;
else resultBuilder.append("\n")
resultBuilder.append(token);
}
String result = resultBuilder.toString();
答案 1 :(得分:1)
这是一个简单的答案
StringBuilder builder = new StringBuilder();
for (String line: new LinkedHashSet<String>(Arrays.asList(inputString.split("\n"))) ) {
builder.append(line);
}
String result = builder.toString();
答案 2 :(得分:0)
合适的方法是使用一套。这将允许您过滤字符串集合并排除重复的值。例如:
import java.util.*;
class Sorter
{
public static void main(String[] args)
{
// The input string, this example uses groups of comma separated values
String input = "EEE,EEE,AAA,BBB,CCC,BBB,DDD,CCC";
// Create a new set, this will be used for filtering
Set<String> set = new HashSet<String>();
// Add each string within input, add to set.
// Repeated values will be
for (String s: input.split(","))set.add(s);
// Format results
for (String s: set) System.out.println(s);
}
}
答案 3 :(得分:0)
使用Scanner(如StringBuffer)和LinkedHashset搜索重复行。
String text = "Eds\r\nIsa\r\nEds\nIsa\r\nEds\nIsa";
StringBuilder textResult = new StringBuilder();
Set list = new LinkedHashSet<String>();
Scanner scanner = new Scanner(text);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(!list.contains(line)){
list.add(line);
textResult.append(line).append(System.getProperty("line.separator"));
}
}
scanner.close();
System.out.println(textResult);