Shift a character forward by three spaces in C

Viewed 54

Write a function that, using the strrot function, modifies each string of the given array s out of n strings. The function prototype is:

void rot_all(char *s[], int n);

Here's my code I only don't know how to do the last function.

char rot3(char c) // Function shifts a letter by three spaces (eg 'a' -> 'd')
{
    if (c >= 'A' && c <= 'Z') return c += 3;
    if (c >= 'a' && c <= 'z') return c += 3;
    return c;
}


void strrot(char *str)
{
    int d = strlen (str);
    for (int i = 0; i < d; i++)
    {
        str[i] = rot3(str[i]);
    }
}

void rot_all(char *s[], int n)
{
    
}

int main ()
{
    char str[23];
    scanf("%s",str);
    strrot(str);
    printf("%s",str);
    return 0;
}
1 Answers

The assumption is that c is a either lower or upper case letter. Using an assert() to document this.

#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char rot3(char c) {
    assert(isalpha(c));
    char offset = isupper(c) ? 'A' : 'a';
    return offset + (c - offset + 3) % ('Z' - 'A' + 1);
}

void strrot(char *str) {
    for (int i = 0; str[i]; i++) {
        str[i] = rot3(str[i]);
    }
}

void rot_all(char *s[], int n) {
    for(int i = 0; i < n; i++) {
        strrot(s[i]);
    }
}

int main () {
    char *strs[] = {
        strdup("Hello"),
        strdup("World")
    };
    rot_all(strs, sizeof(strs) / sizeof(*strs));
    for(int i = 0; i < sizeof(strs) / sizeof(*strs); i++) {
        printf("%s\n", strs[i]);
        free(strs[i]);
    }
    return 0;
}

and the output is:

Khoor
Zruog
Related