Delete duplicate strings in string array

后端 未结 13 2022
执念已碎
执念已碎 2020-12-30 00:33

I am making a program based on string processing in Java in which I need to remove duplicate strings from a string array. In this program, the size of all strings are same.

相关标签:
13条回答
  • 2020-12-30 00:53

    Why didn't you remove the most inner loop with in favor of String.equals(String)?

    In first iteration you are comparing array[0] with array[0] which are equal, and it would be removed. Then you will compare the original array[1] with all other elements in array, and if they are equal, you are removing array[1] (not the other one).

    There are some problems, if there are some duplicate Strings, you are removing the first one, which will reduce the size of the array without reducing r so, some of the Strings in the array are skipped.

    I would use a data structure which forces uniqueness, such as a Set.

    What will happen if you have 3 equal Strings in your array, I'm not sure what will happen.

    I believe you would encounter some ArrayIndexOutOfBoundsExceptions.

    0 讨论(0)
  • 2020-12-30 01:02
    Sring[] myStringArray = {"hello", "hello", "moto"};
    String[] filteredArray = new LinkedHashSet<String>(Arrays.asList(myStringArray))
                             .toArray(new String[0]);
    
    System.out.println("filteredArray Size: " + filteredArray.length);
    System.out.println("filteredArray[0] = " + filteredArray[0]);
    System.out.println("filteredArray[1] = " + filteredArray[1]);
    
    0 讨论(0)
  • 2020-12-30 01:03

    Unless this is [homework] I would use a Set

    String[] array =
    Set<String> uniqueWords = new HashSet<String>(Arrays.asList(array));
    
    0 讨论(0)
  • 2020-12-30 01:04
    • Why don't you use String.equals() for comparison instead of iterating through the characters in the strings manually?
    • Your logic is actually flawed: for array[s] == "12345" and array[m] == "123" it would claim that they are equal
    • moreover, in your inner loop for(int m=0;m<array.length;m++) m will also become equal to s at some point, so you will compare a string to itself

    These notes assume that you need to implement the removal logic with your own code, not being allowed to use the class library. If this is not the case, as others noted, using a HashSet is the simplest approach.

    0 讨论(0)
  • 2020-12-30 01:09
    import java.util.*;
    public class Stringarray {
    
        public static void main(String args[]){
    
            String[] name = {"aim","rajesh","raju","aim"};
    
        Set<String> myset  = new HashSet<String>();
        Collections.addAll(myset,name);
    
           System.out.println(myset);
        }
    }
    
    0 讨论(0)
  • 2020-12-30 01:09

    I think the if condition at the end should be if(n==(array[m].length()-1))

    Having said that, you seem to be trying to implement what String.equals() method does in your inner most loop.

    0 讨论(0)
提交回复
热议问题