CharConvert

Write a program that reads a string and a character. Each occurrence of the given character (regardless of its case) is converted to opposite case.
INPUT: AabrAcadabrA and ‘a’
OUTPUT: aAbracAdAbra ( see each ‘a’ or ‘A’ is converted to opposite case ie. upper to lower or vice-versa

import java.util.Scanner; 
public class StringC
{
    private String txt;
    private int n;
    private char ch;
    public void accept()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter text ");
        txt = sc.nextLine();
        n= txt.length();
        System.out.println("Enter a character ");
        ch = sc.next().charAt(0);       
    }
    public void convert()
    {
        int i;
        String st="";
        for(i=0;i<n;i++)
        {
            char cr=txt.charAt(i);
            char cu=Character.toUpperCase(ch);
            char cl=Character.toLowerCase(ch);
            if(cr==cu || cr==cl)
            {
                if(cr>='A' && cr<='Z')
                    st=st+(char)(cr+32);
                if(cr>='a' && cr<='z')
                     st=st+(char)(cr-32);  
           }
           else
                st=st+cr;              
        }
        System.out.println("New text is : "+st);        
   }
   public void main()
   {
       StringC A = new StringC();
       A.accept();
       A.convert();
    }
}
This entry was posted in String. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *