[ create a new paste ] login | about

Link: http://codepad.org/7Jb5d8Cx    [ raw code | output | fork | 1 comment ]

mohit_at_codepad - C, pasted on Mar 16:
// http://codepad.org/udoDscmx
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#define LOCAL_FUNC static 

LOCAL_FUNC char *starrule(char *str)
{
  char *first = str;
  char *next;
  int otherrulecontext = 0;
  if(*first != '\0')
  {
    for(next = first + 1; *next != '\0'; ++first, ++next)
    {
      if( !isalpha(*first) ) otherrulecontext = 1;
      else {
        if( !otherrulecontext
            && (*first == *next) ) *first = '*';
        otherrulecontext = 0; 
      }
    }
  }
  return str; 
}


LOCAL_FUNC char *dashrule(char *str)
{
  char *first = str;
  char *next;
  int otherrulecontext = 0;
  if(*first != '\0')
  {
    for(next = first + 1; *next != '\0'; ++first, ++next)
    {
      if( !isalpha(*first) ) otherrulecontext = 1;
      else {
        if( !otherrulecontext
            && (*first + 1 == *next) ) *first = '-';
        otherrulecontext = 0; 
      }
    }
  }
  return str; 
}

LOCAL_FUNC char *applyrules(char *str)
{
  char *pc = str;
  do { if(!isalpha(*pc) ) return ""; } while(*++pc != '\0');
  /* Optimization note: For n rules, this method does n pass */
  /* You can parse multiple rules (and even print) simultaneoulsy */
  /* But it would take away the redability */
  /* Don't do it, unless this module is performance bottleneck */
  return dashrule( starrule (str) );
}

LOCAL_FUNC void printruled(char *str)
{
  int stars = 0;
  int dashes = 0;
  char *pc = str;

  if(!str) return;
  do
  {
    switch(*pc) {
      case '-' : ++dashes; break;
      case '*' : ++stars; break;
      default:
        if(dashes) printf("%c-%c", *pc-dashes, *pc);
        else if(stars) printf("%c*%d", *pc, 1 + stars);
        else printf("%c", *pc);
        stars = dashes = 0;
        if(pc[1] != '\0') printf(", ");
        else printf("\n");
    } 
  }while(*++pc != '\0');
}

LOCAL_FUNC void groupchars(char *str) {
  size_t length = strlen(str);
  char *copy = malloc(length + 1);
  strcpy(copy, str);
  printruled( applyrules(copy) );
  free(copy);
}

int main(int argc, char *argv[])
{
  int i;
  if(argc == 1) { // dummy
    groupchars("aaaabcdepqrrraa");
    return 1;
  } else for(i = 1; i < argc; ++i) groupchars(argv[i]);
  return 0;
}

/* EOF */


Output:
1
a*4, b-e, p-q, r*3, a*2


Create a new paste based on this one


Comments:
posted by mohit_at_codepad on Mar 20
Review Comments: Functions starrule and dashrule are almost similar. One can use something like strategy design pattern or some function pointer (containing change between two functions) as argument to a function containing common body.
reply