Search code examples
cfunctioncharreversec-strings

how to reverse string in array in C


I have exercise to use for loop to initialization 1 string array from A to Z and then Z to A.

I was successful to print from A to Z but print Z to A not working. So i need to help in this code.

char *problem58()
{
    char temp, *result = (char *)malloc(52 * sizeof(char));
    int left = 0, right = 52 - 1;

    for (char i = 'A'; i <= 'Z'; i++)
    {
        result[left] = i;
        printf("%c", i);
        left++;
    }
    // this is my idea to reverse this string
    for (int i = left; i < right; i++)
    {
        temp = result[left];
        result[left] = result[right];
        result[right] = temp;
        printf("%c", result[right]);
        right--;
    }
    return result;
}

line code run in terminal: ABCDEFGHIJKLMNOPQRSTUVWXYZSW\:C=cepSmoC


Solution

  • Here is my answer

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    char* problem58()
    {
        int n = 0;
        int left = 0, right = 52 - 1;
    
        // A--->Z and Z--->A total number is 52, because string end with '\0'(0), so add 1 is 53.
        char* result = (char*)malloc(53 * sizeof(char));
    
        // Check if it is possible to dynamically allocate memory for 53 variables of type "char"
        // You can also write like this: if(result == NULL)
        if(NULL == result){
            printf("No space\n");
            exit(1);
        }
    
        // Initial result with 0,because string end with ('\0')0.
        // So result[0] will be 0, result[1] will be 0 ...... result[52] will be 0
        for(int m = 0; m < 53;m++){
            result[m] = 0;
        }
    
        for (char i = 'A'; i <= 'Z'; i++)
        {
            result[left] = i;
            //printf("%c", i);
            left++;
        }
    
        // Now left is 26, reset it to 0, because result[0] is 'A'
        left = 0;
    
        // n is execute times, need to let result[51] = result[0] = 'A', and result[50] = result[1] = 'B' ......
        //so right-- and left++
        for (n = 0; n < 26; n++)
        {
            result[right] = result[left];
            right--;
            left++;
        }
        return result;
    }
    
    int main()
    {
    
        char* str = problem58();
        printf("str's length is %ld\n",strlen(str));
        printf("%s\n",str);
        free(str);
        return 0;
    }
    

    Run it will output

    str's length is 52
    ABCDEFGHIJKLMNOPQRSTUVWXYZZYXWVUTSRQPONMLKJIHGFEDCBA