Showing posts with label String Programs. Show all posts
Showing posts with label String Programs. Show all posts

Saturday, 24 September 2016

Java Program to sort Names in an alphabetical order.

Java program to sort Names in an alphabetical order
    Example:  input- 4
                    happy lucky abhay sibu
              output-abhay happy lucky sibu
 
    Example 2: input- 4 
                     arjun hapi babai lucky
               output-arjun babai hapi lucky 

Answer :

 public class SortNames
 {

  public static void main(String[] args) 
  {
        Scanner sc=new Scanner(System.in);
        System.out.println();
        
        int num=sc.nextInt();// how many names you want to sort 

        String[] s=new String[num];

        for(int i=0;i<(num);i++)
        {
           s[i]=sc.next();
        }

       int len=s.length;

       for(int i=0;i<(len);i++)
       {
          String temp;
          for(int j=0;j0)
              {
                  temp=s[j];
                  s[j]=s[j+1];
                  s[j+1]=temp;
              }
          }
       }

       for(String m:s)
       {
          System.out.print(m+" ");
       }
  }

 }

Thursday, 15 September 2016

Java program to remove duplicate character from a String

Java program to remove duplicate character from a String
    Example: input-aabcdefsdd
             output-abcdefs
    Example2:input-feedback
             output-fedback

Answer :

public class Pattern5 
{

 public static void main(String[] args) 
 {
   Scanner sc=new Scanner(System.in);
   System.out.println("Enter the String");
    String s=sc.next();
  
     String[] nt=s.split("");
     String result=nt[0];
  
     for(int i=0;i<(nt.length);i++)
     {
        if(!result.contains(nt[i]))
        {
            result=result+nt[i];
        }
   
     }
     System.out.println(result);
 }

}

Tuesday, 23 August 2016

Java Program to swap first and last word of a Sentence

Java Program to swap first and last word of a Sentence

Answer :

import java.util.Scanner;

public class StringWordSwap {

 public static void main(String[] args) {
 
  
  Scanner scan=new Scanner(System.in);
  System.out.println("Enter the String :");
  String s=scan.nextLine();
  String[] ori=s.split(" ");
//split method return type is array type. Example-if input is "give your best performance"
                          //after split method ori[]={"give","your","best","performance"};
  String temp=ori[0];                    
  
  ori[0]=ori[ori.length-1]; //"performance" will store at ori[0]
  
   ori[ori.length-1]=temp;//"give" will store at last index    
  
  for(int i=0;i<(ori.length);i++){
   System.out.print(ori[i]+" ");
  }

 }
}
Example:
 input:give your best performance
 ouput:performance your best give