有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何删除字符串中的重复项,例如:“我的名字是这个和那个这个和那个”输出将是“我的名字是这个和那个”

我试过这个

公共静态无效重复删除程序(){ //从用户中删除字符串中的所有重复单词

//ask the user to enter his/her input
System.out.println("Enter your sentence: ");

//get user input
Scanner string = new Scanner(System.in);
String UserInput  = string.nextLine();

//add comas into string and create an array
String[] arrayString = UserInput.split(",");

System.out.print(Arrays.toString(arrayString));

//create a new array that stores the non duplictes
String[] newArray = new String[arrayString.length];
Arrays.asList(newArray);
    
//loop through array to find duplicates
for (int i = 0 ; i < arrayString.length; i ++){
 for (int j = 0; i < arrayString.length; i ++){
    //try to remove duplicates
 if (i != j){

//这是我正在努力解决的问题,在循环通过数组后,我如何删除重复项

 String a = Integer.toString(i);
  String b = Integer.toString(j);
  
  newArray.add(a);
 
 
 }

共 (2) 个答案

  1. # 1 楼答案

    这似乎是更简单的方法:

        List<String> arr = Arrays.asList(source.split("\\s"));
        Set<String> distincts = new LinkedHashSet<>(arr);
        String result String.join(" ", distincts);
    

    使用Java8流重写上述内容

        public void duplicateRemover() {
            String source = "my name is this and that this and that";
            List<String> distincts = Arrays.stream(source.split("\\s")).distinct().collect(Collectors.toList());
            String result = String.join(" ", distincts);
            System.out.println(result);
        }
    
  2. # 2 楼答案

    在阵列中,它将工作

    public class RemoveDuplicateInArrayExample{  
    public static int removeDuplicateElements(int arr[], int n){  
        if (n==0 || n==1){  
            return n;  
        }  
        int[] temp = new int[n];  
        int j = 0;  
        for (int i=0; i<n-1; i++){  
            if (arr[i] != arr[i+1]){  
                temp[j++] = arr[i];  
            }  
         }  
        temp[j++] = arr[n-1];     
        // Changing original array  
        for (int i=0; i<j; i++){  
            arr[i] = temp[i];  
        }  
        return j;  
    }  
       
    public static void main (String[] args) {  
        int arr[] = {10,20,20,30,30,40,50,50};  
        int length = arr.length;  
        length = removeDuplicateElements(arr, length);  
        //printing array elements  
        for (int i=0; i<length; i++)  
           System.out.print(arr[i]+" ");  
    }  
    

    }