Skip to main content
deleted 28 characters in body; edited tags
Source Link
Jamal
  • 35.2k
  • 13
  • 134
  • 238

a string String case reverse function in C

This is my program. All it does is reversereverses the case of a character in a string. a (a string being an array of characters). How does it look? Anything I can improve on? Besides documentation. In, in particular, any thoughts on the type casting found in str_case_rev?

a string case reverse function in C

This is my program. All it does is reverse the case of a character in a string. a string being an array of characters. How does it look? Anything I can improve on? Besides documentation. In particular, any thoughts on the type casting found in str_case_rev?

String case reverse function in C

This reverses the case of a character in a string (a string being an array of characters). How does it look? Anything I can improve on? Besides documentation, in particular, any thoughts on the type casting found in str_case_rev?

Source Link
Ryan
  • 521
  • 1
  • 5
  • 14

a string case reverse function in C

This is my program. All it does is reverse the case of a character in a string. a string being an array of characters. How does it look? Anything I can improve on? Besides documentation. In particular, any thoughts on the type casting found in str_case_rev?

#include <stdio.h>  // fprintf
#include <stdlib.h> // malloc
#include <string.h> // strlen
#include <ctype.h>  // toupper, tolower

/*
 * a string is an array of characters, in C, all arrays
 * are always passed never passed value, always a pointer to
 * the variable
 * This is why the caller does not need to call the function like:
 * camel_case_rev(src, &dest, len)
 *
 * Since here the array of characters ("a string") is already being
 * passed as a pointer value
 */
void str_case_rev(const char *src, char *dest, size_t len)
{
        size_t i = 0;

        for(; i < len; i++)
        {
                if(src[i] <= 'Z' && src[i] >= 'A')
                {
                        *(dest + i) = (char)tolower((int)src[i]);
                }
                else if(src[i] <= 'z' && src[i] >= 'a')
                {
                        *(dest + i) = (char)toupper((int)src[i]);
                }
                else
                {
                        *(dest + i) = src[i];
                }
        }

        i++;
        *(dest + i) = '\0';
}

int main(int argc, char **argv)
{
        if(argc < 2)
        {
                fprintf(stderr, "Usage: %s <string>\n", argv[0]);
                return EXIT_FAILURE;
        }

        char *dest = NULL;

        size_t len = strlen(argv[1]);

        dest = malloc(len + 1);

        if(NULL == dest)
        {
                fprintf(stderr, "Memory error\n");
                return EXIT_FAILURE;
        }

        str_case_rev(argv[1], dest, len);

        fprintf(stdout, "%s\n", dest);

        free(dest);

        return EXIT_SUCCESS;
}