Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

หาตัวอักษรที่ไม่ซ้ำกันจากทั้งสอง String และต่อกันด้วย Java

ตัวอย่างโค้ด

import java.util.*;
import java.lang.*;
import java.io.*;

public class Demo {
    public static String concat_str(String str_1, String str_2) {
        String result = "";
        int i;
        HashMap my_map = new HashMap();
        
        for (i = 0; i < str_2.length(); i++)
            my_map.put(str_2.charAt(i), 1);
            
        for (i = 0; i < str_1.length(); i++)
            if (!my_map.containsKey(str_1.charAt(i)))
                result += str_1.charAt(i);
            else
                my_map.put(str_1.charAt(i), 2);
                
        for (i = 0; i < str_2.length(); i++)
            if (my_map.get(str_2.charAt(i)) == 1)
                result += str_2.charAt(i);
                
        return result;
    }

    public static void main(String[] args) {
        String my_str_1 = "ABMCD";
        String my_str_2 = "MNCPQR";
        System.out.println("The uncommon values concatenated from both strings is : ");
        System.out.println(concat_str(my_str_1, my_str_2));
    }
}

ผลลัพธ์

The uncommon values concatenated from both strings is : ABDNPQR

คลาส Demo มีฟังก์ชัน concat_str รับสตริง 2 ตัว สร้าง HashMap เก็บตัวอักษรของสตริงที่ 2 พร้อมค่า 1 วนลูปสตริงที่ 1 หากตัวอักษรไม่อยู่ใน map ให้ต่อท้าย result หากอยู่แล้ว อัปเดตค่าเป็น 2 (หมายถึงซ้ำ) วนลูปสตริงที่ 2 อีกครั้ง หากค่าใน map เป็น 1 (อยู่ในสตริงที่ 2 เพียงอย่างเดียว) ให้ต่อท้าย result คืนค่า result ที่เป็นตัวอักษรที่ไม่ซ้ำกันจากทั้งสองสตริง