Remove duplicate values from a string in java

前端 未结 14 2598
刺人心
刺人心 2020-12-06 05:26

Can anyone please let me know how to remove duplicate values from

String s=\"Bangalore-Chennai-NewYork-Bangalore-Chennai\"; 

and output sh

相关标签:
14条回答
  • 2020-12-06 06:21
    import java.util.*;
    
    public class RemoveDuplicateWord {
    
        public static void main(String[] args) {
            String str = "Hai hello Hai how hello are how you";
            removeDupWord(str);
        }
    
        public static void removeDupWord(String input) {
            List<String> list = Arrays.asList(input.split(" "));
            LinkedHashSet<String> lhs = new LinkedHashSet<String>(list);
            for(String s : lhs) {
                System.out.print(s+" ");
            }                   
        }
    }
    
    0 讨论(0)
  • 2020-12-06 06:22

    You could add your strings to a HashSet.

    1. Split the strings on a "-".
    2. Store the individual words in Array. i.e arr[]

    Sinppet :

    Set<String> set = new HashSet<String>();
    
        for(int i=0; i < arr.length; i++){
          if(set.contains(arr[i])){
            System.out.println("Duplicate string found at index " + i);
          } else {
            set.add(arr[i]);
          }
    
    0 讨论(0)
提交回复
热议问题