Thursday 22 March 2018

Java Program For String Example

If I enter String 'aabbccddefgh' the output should be as below.

Output = 2a2b2c2d1e1f1g1h


public class JavaExampleString1 
{

 public static void main(String[] args)
 {
  String temp = "aabbccddefhg";
  String output = "";
    
  System.out.println(temp.length());
  System.out.println("Input String : " + temp);
  int vCounter = 1;
  for(int i=0; i<temp.length(); i++)
  {
   if(i<(temp.length()-1))
   {
    if(temp.charAt(i) == temp.charAt(i+1))
    {
     vCounter++;
    }
    else
    {    
     output = output + Integer.toString(vCounter) + temp.charAt(i);
     //System.out.println(output);
     vCounter = 1;
    }
   }
   else
   {
    output = output + Integer.toString(vCounter) + temp.charAt(i);
   }
      
  }
  
  System.out.println("Output String : " + output);

 }

}

No comments:

Post a Comment

Popular