Sunday, February 10, 2013

Strings Questions






 Problem 1 : Write a program to Run Length Encoding of a given Input String. 
    Sample Input : "aaaadddddaaaaaaauuuuiiiii"
    Sample Output: "a4d5a7u4i5"

Solution : 

#include
#include

char* runLenEnc(char *str) {
      int i,j=0,len = 0,count = 1;
      char *str1;
      for (i =0; str[i] != '\0' ; i++) len++;
      printf("length = %d\n" , len);
      str1 = (char*) malloc(2*len*sizeof(char));
      for ( i =0 ; str[i]!= '\0' ; i++) {
           str1[j++] = str[i];
           while (str[i] == str[i+1]) {
             count++;
             i++;
           }
           if (count > 9) {
               int temp, numChar =0;
               temp = count;
               while(temp) {
                     numChar++;
                     temp /=10;
               }
               printf("numChar = %d, str[%d] = %c\n", numChar, j-1, str[j-1]);
               j+=(numChar-1);
               while (count) {
                     str1[j--] = count%10 + '0';
                     count /=10;
               }
               j+=(numChar+1);
           } else {
               str1[j++] = count + '0';
           }
           count = 1;
      }
   
      str1[j] = '\0';
      return str1;
}
          
int main() {
   char strIn[] = "aaaadddddaaaaaaauuuuiiiii";
   char *strOut;
   strOut = runLenEnc (strIn);
   printf("Run Length Encoding O/P : %s", strOut);
   getch();
}  



/* write a program to reverse the string in place */ 

 #include<iostream>
 #include<string.h>
 using namespace std;
 void reverse(string& str) {
    int i,j;
    char temp;
    int len =0;
    for(i=0; str[i] !='\0';i++)
        len++;
    for(i=0,j=len-1;i<j;i++, j--){
         temp = str[i];
         str[i] = str[j];
         str[j] = temp;
     }
 }
 int main() {
     string str;
     cout<<"Enter the string: ";
     if(!getline(cin, str))
         getline(cin,str);
     reverse(str);
     cout<<str<<endl;
     return 0;
 }


/* recursive way to print the string in reverse order */

------
----
--