Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- [sort_char.c]
- Author : AlexZ ( alessandro.suglia@gmail.com )
- Date : 30/09/2011 07:57 PM
- Simple program which takes an undefined
- length string and sort alphabetically each
- of its char.
- */
- /* <------------Header Functions Declaration -----------------> */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- /* <-----------Functions Declarations -----------------------> */
- char *sort_char( const char * );
- int count_argv( char *argv[], int argc );
- char *strcat_argv( char *s, int len, char *argv[], int argc );
- /* <------------- main.c ------------------------------------> */
- int main(int argc, char *argv[] )
- {
- char *s = NULL;
- int len = 0; /* variable which holds the entire length of the argument passed through the command line*/
- if ( argc < 2 ) /* Too few arguments, something was wrong */
- {
- perror("<<<<USAGE<<<<< : ./ord_char 'word'\nTry again passing a string\n");
- exit(-1);
- }
- len = count_argv(argv, argc); /* call to the function count_argv */
- s = strcat_argv(s, len, argv, argc); /* call to the function strcat_argv */
- if ( !(s) ) /* Memory Allocation test */
- {
- perror("Malloc error : FATAL ERROR!\n");
- exit(-1);
- }
- s = sort_char(s); /* Call ord_char function */
- printf("SORTED STRING %s : %s\n", argv[1],s);
- return EXIT_SUCCESS;
- }
- /* Count the number of argument that were passed through the command line */
- int count_argv( char *argv[], int argc)
- {
- int i;
- int len = 0;
- for ( i = 1; i < argc; i++ )
- len += strlen(argv[i]);
- return len;
- }
- /* Concatenates the command line arguments in a single string */
- char *strcat_argv( char *s, int len, char *argv[], int argc )
- {
- int i;
- s = (char*)malloc(len * sizeof(char));
- if ( !(s) )
- {
- perror("Malloc error : FATAL ERROR!\n");
- exit(-1);
- }
- for ( i = 1; i < argc; i++ )
- strcat(s, argv[i]);
- return s;
- }
- /* Sorts alphabetically each string's char */
- char *sort_char( const char *s )
- {
- int i;
- int high = strlen(s);
- char *str;
- char c;
- str = (char*)malloc(high * sizeof(char));
- if ( !(str) )
- {
- perror("MALLOC ERROR : Fatal!\n");
- exit(-1);
- }
- strcpy(str, s);
- /* Simple bubble sort implementation */
- while ( high > 1 )
- {
- for ( i = 0; i < high-1; i++ )
- if ( str[i] > str[i+1] )
- {
- c = str[i];
- str[i] = str[i+1];
- str[i+1] = c;
- }
- high--;
- }
- return str;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement