13 June 2018

Reverse each word in a given string



Example:
Input:
2
i.like.this.program.very.much
pqr.mn

output:
i.ekil.siht.margorp.yrev.hcum
rqp.nm 
 
public class NewClass10 {
    void print(String s)
    {
        System.out.println(s);
    }
    String reverse(String s,int i,int j)
    {
        char c[]=s.toCharArray();
        while(i<j)
        {
            char t=c[i];
            c[i]=c[j];
            c[j]=t;
            i++;
            j--;
        }return s.valueOf(c);
    }
    String dot(String s)
    {  int e=0;
        for(int i=0;i<s.length();i++)
        {
            if(s.charAt(i)=='.')
            {
               s=reverse(s,e,i-1);
               e=i+1;
            }
            if(s.charAt(i)==s.charAt(s.length()-1))
            {
                s=reverse(s,e,i);
            }
        }
        return s;
    }

    public static void main(String args[])
    {
        String s="i.ekil.siht.margorp.yrev.hcum";
        NewClass10 ob=new NewClass10();
        s=ob.dot(s);
        ob.print(s);
    }
}

No comments:

Post a Comment