Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- enum _error_codes {
- NO_ARGS_ERR = -1,
- JOINING_ERR = -2
- };
- /* Function Declerations */
- char *join_args(size_t, char *[], const char);
- void swap(char *, char *);
- void reverse(char *, size_t);
- char *reverse_words(char *, const char);
- int main(int argc, char *argv[]) {
- argc--; argv++;
- if (!argc)
- return NO_ARGS_ERR;
- char *joined = join_args(argc, argv, ' ');
- if (joined == NULL)
- return JOINING_ERR;
- printf("Reversed: %s\n", reverse_words(joined, ' '));
- free(joined);
- return 0;
- }
- /* Function Definitions */
- char *join_args(size_t size, char *args[], const char delimiter) {
- if (!size) return NULL;
- size_t allocation_size = 0;
- size_t arg_lengths[size];
- // Accumulate allocation size and determine the lengths of each argument
- for (int i = 0; i < size; i++) {
- arg_lengths[i] = strlen(args[i]);
- allocation_size += arg_lengths[i] + 1;
- }
- // Allocate memory and combine arguments
- char *ret = malloc(allocation_size), *ptr = ret;
- for (int i = 0; i < size; i++) {
- strcpy(ptr, args[i]);
- ptr[ arg_lengths[i] ] = ' ';
- ptr += arg_lengths[i] + 1;
- }
- *--ptr = '\0';
- return ret;
- }
- void swap(char *a, char *b) {
- char temp = *a;
- *a = *b;
- *b = temp;
- }
- void reverse(char *str, size_t size) {
- if (!size) return;
- unsigned left = 0, right = size - 1;
- while (left < right)
- swap(&str[left++], &str[right--]);
- }
- char *reverse_words(char *str, const char delimiter) {
- char *ret = str;
- size_t index = 0;
- // Reverse the entire string then reverse the characters of
- // every word seperated by the delimiter or up to the NULL-terminator
- reverse(str, strlen(str));
- while (str[index] != '\0') {
- if (str[index] == delimiter) {
- reverse(str, index);
- str += index + 1;
- index = 0;
- continue;
- }
- index++;
- }
- reverse(str, index);
- return ret;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement