Search code examples
javastringbuilder

Replace consonants of a String with @ symbol


Question is to convert all consonants in given string to @ here I have used string builder to take input but while convertion all characters in string get converted to @ why is that please help?

import java.util.Scanner;

public class Sample 
{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        StringBuilder str2= new StringBuilder(sc.nextLine());
        
        for(int i=0;i<str2.length();i++)
        {
            if(str2.charAt(i)!='a'||str2.charAt(i)!='e'||str2.charAt(i)!='i'||str2.charAt(i)!='o'||str2.charAt(i)!='u'||str2.charAt(i)!='A'||str2.charAt(i)!='E'||str2.charAt(i)!='I'||str2.charAt(i)!='O'||str2.charAt(i)!='U'||str2.charAt(i)!=' ')   
            {
                str2.setCharAt(i,'@');
            }
        }
        System.out.println(str2);
    }

}

sample input - aacaaaa Expected output - aa@aaaa

output from above program - @@@@@@@


Solution

  • Try this out, putting all the vowels into a list makes your code much easier to read.

    import java.util.Arrays;
    import java.util.Scanner;
    
    public class main {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            System.out.println("Enter the string to check");
            String checkString = in.nextLine();
            StringBuilder builder = new StringBuilder();
            String[] vowels = new String[] { "a", "e", "i", "o", "u" };
    
            if (checkString != ""){
                String[] check = checkString.split("");
                for (String c : check){
                    if (!Arrays.asList(vowels).contains(c.toLowerCase()) || c.equals(" ")){
                        builder.append("@");
                    } else {
                        builder.append(c);
                    }
                }
            }
            System.out.println(builder);
        }
    }