Remove specific characters from string in Java

前端 未结 3 1166
孤城傲影
孤城傲影 2021-02-20 00:28

For example, given a string of Battle of the Vowels:Hawaii vs Gronzy when we specify the characters to be removed as aeiou, the function should transfo

3条回答
  •  悲哀的现实
    2021-02-20 00:45

    public class RemoveCharacters
    {
        static String removeCharsFromString(String word1, String word2)
        {
            StringBuilder sb = new StringBuilder(word1);
    
            System.out.println(sb);
            //char[] word2characters= word2.toCharArray();
            HashMap table = new HashMap();
    
            for (int i = 0; i < word2.length(); i++)
            {
                table.put(word2.charAt(i), 1);
    
            }
    
            int p = 0;
            for (int i = 0; i < word1.length(); i++)
            {
    
                if (table.containsKey(word1.charAt(i)))
                {
                    if (p == 0)
                    {
                        sb.deleteCharAt(i);
                        //p++;
                    }
                    else
                    {
                        sb.deleteCharAt(i - p);
                    }
                    //System.out.println(sb);
                    p++;
                }
    
            }
    
            return sb.toString();
        }
    
        public static void main(String[] args)
        {
            System.out.println("Enter your string");
            Scanner sc = new Scanner(System.in);
            String originalword = sc.nextLine();
    
            System.out.println("Enter the remove string");
            Scanner sc1 = new Scanner(System.in);
            String removecharacters = sc1.nextLine();
    
            String result = removeCharsFromString(originalword, removecharacters);
    
            System.out.println(result);
        }
    }
    

提交回复
热议问题