gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:48:50 24 4
gpt4 key购买 nike

如何在不使用 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];
}
}

最佳答案

1)我认为您需要使用等于运算符。尝试

if (!wordList[i].equals(wordList[j])){

而不是 != .

2) 凯文也是对的。您需要将 t 设置回 false。

3) 其他人已经指出的旁注:为了提高效率,您应该使用

开始内部循环
for (j = i+1; j < wordList.length; j++) {

4) 另一个旁注:您的结果数组仍然太长。如果你不想使用 List<String>并且可以按照 Zim-Zam O'Pootertoot 的建议使用解决方案松开原始数组并将原始副本设置为空,添加一个计数器要计算您分配了多少空值,请使用正确的大小初始化新数组并在第一个数组上循环最后一次并仅将非空值复制到新数组中。

关于java - 从数组中删除重复的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16175401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com