Advertisement
Guest User

C Challenge

a guest
Apr 11th, 2023
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.09 KB | Source Code | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. enum _error_codes {
  6.     NO_ARGS_ERR = -1,
  7.     JOINING_ERR = -2
  8. };
  9.  
  10. /* Function Declerations */
  11.  
  12. char *join_args(size_t, char *[], const char);
  13. void swap(char *, char *);
  14. void reverse(char *, size_t);
  15. char *reverse_words(char *, const char);
  16.  
  17. int main(int argc, char *argv[]) {
  18.     argc--; argv++;
  19.     if (!argc)
  20.         return NO_ARGS_ERR;
  21.  
  22.     char *joined = join_args(argc, argv, ' ');
  23.     if (joined == NULL)
  24.         return JOINING_ERR;
  25.  
  26.     printf("Reversed: %s\n", reverse_words(joined, ' '));
  27.  
  28.     free(joined);
  29.     return 0;
  30. }
  31.  
  32. /* Function Definitions */
  33.  
  34. char *join_args(size_t size, char *args[], const char delimiter) {
  35.     if (!size) return NULL;
  36.  
  37.     size_t allocation_size = 0;
  38.     size_t arg_lengths[size];
  39.  
  40.     // Accumulate allocation size and determine the lengths of each argument
  41.     for (int i = 0; i < size; i++) {
  42.         arg_lengths[i] = strlen(args[i]);
  43.         allocation_size += arg_lengths[i] + 1;
  44.     }
  45.  
  46.     // Allocate memory and combine arguments
  47.     char *ret = malloc(allocation_size), *ptr = ret;
  48.     for (int i = 0; i < size; i++) {
  49.         strcpy(ptr, args[i]);
  50.         ptr[ arg_lengths[i] ] = ' ';
  51.         ptr += arg_lengths[i] + 1;
  52.     }
  53.     *--ptr = '\0';
  54.     return ret;
  55. }
  56.  
  57. void swap(char *a, char *b) {
  58.     char temp = *a;
  59.     *a = *b;
  60.     *b = temp;
  61. }
  62.  
  63. void reverse(char *str, size_t size) {
  64.     if (!size) return;
  65.  
  66.     unsigned left = 0, right = size - 1;
  67.     while (left < right)
  68.         swap(&str[left++], &str[right--]);
  69. }
  70.  
  71. char *reverse_words(char *str, const char delimiter) {
  72.     char *ret = str;
  73.     size_t index = 0;
  74.  
  75.     // Reverse the entire string then reverse the characters of
  76.     // every word seperated by the delimiter or up to the NULL-terminator
  77.     reverse(str, strlen(str));
  78.     while (str[index] != '\0') {
  79.         if (str[index] == delimiter) {
  80.             reverse(str, index);
  81.             str += index + 1;
  82.             index = 0;
  83.             continue;
  84.         }
  85.         index++;
  86.     }
  87.     reverse(str, index);
  88.  
  89.     return ret;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement