小编典典

从数组中删除重复的字符串?

java

如何在不使用HashSet的情况下从字符串数组中删除重复的字符串?

我尝试使用循环,但是单词不能删除。

StringBuffer outString = new StringBuffer("Our, aim, and, isn't, easy, you, you're, actual, and, are, aren't, and, improve, achieving, and, Obviously, and, illumination, are");

wordList = outString.toString().split(", ");
for (i = 0; i < wordList.length; i++) {
  for (j = 0; j < wordList.length; j++) {
    if((wordList[i]!=wordList[j])&&(j>i)){
      t=true;
    }
  }
  if(t==true){
    k++;
  }
}
String[] wordList1 = new String[k];
wordList = outString.toString().split(", ");
for (i = 0; i < wordList.length; i++) {
  (j = 0; j < wordList.length; j++) {
    if((wordList[i]!=wordList[j])&&(j>i)){
      t=true;
    }
  }
  if(t==true){
    wordList1[i]=wordList[i];
  }
}

阅读 228

收藏
2020-11-26

共1个答案

小编典典

尝试使用以下代码删除重复的单词:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < wordList.length; i++) {
    boolean found = false;
    for (int j = i+1; j < wordList.length; j++) {
        if (wordList[j].equals(wordList[i])) {
            found = true;
            break;
        }
    }
    // System.out.printf("Checking: [%s]%n", wordList[i]);
    if (!found) {
        if (sb.length() > 0)
            sb.append(' ');
        sb.append(wordList[i]);
    }
}
System.out.printf("Unique: [%s]%n", sb);
2020-11-26