Reputation: 41
Practicing for an upcoming test in C. Making a program to shift every letter in a string(array of characters in c).
For example if I want to shift 'a' by 3 it would be 'd'. This program works fine however it's kinda of a "brutal force" solution IMO. Any idea how to accomplish this task in a better/more elegant way? using pointers/string library functions/getchar comes to mind but I'm still a novice so not sure how to implement them.
Any idea for a better solution? looking for a guide/idea you don't need to write any code for me. Thanks in advance.
#define N 3
int shifter(char a[],int n,int shift,char b[]);
int main(){
char a[N] = {'h','e','y'};
char b[N];
int shift = 3;
shifter(a,N,shift,b);
int i;
for(i=0;i<N;i++){
printf("%c",b[i]);
}
return 0;
}
int shifter(char a[],int n,int shift,char b[]){
int i;
for(i=0;i<N;i++){
if(a[i]>= 65 && a[i]<=90){
if (a[i]+shift > 90)
b[i] = (a[i]+shift)-26;
}
else b[i] = a[i]+shift;
if (a[i]>=97 && a[i]<= 122){
if(a[i]+shift > 122)
b[i] = (a[i]+shift)-26;
}
else b[i] = a[i]+shift;
}
return b;
}
Upvotes: 0
Views: 96
Reputation: 41
Thank you all for the feedback, I tried to apply it to solving the same problem I posted initially except this time using pointer arithmetic. It functions as intended, hopefully it is improved and could help someone else in the future.
define N 3
int i;
void pointer_shift(char *a,int shift);
int main(){
char a[N] = {'A','b','c'};
int shift = 3;
pointer_shift(a,shift);
return 0;
}
void pointer_shift(char *a,int shift) {
char b[N];
char *p = a;
char *q = b;
for(p=a;p<a+N;p++,q++)
{
if(*p >= 'a' && *p <= 'z')
{
*q = ((*p-'a')+ shift)%26+'a';
printf("%c",*q);
}
else if (*p >= 'A' && *p <= 'Z')
{
*q = ((*p-'A')+ shift)%26+'A';
printf("%c",*q);
}
else { printf(" Error: Not a Letter \n"); break;}
}
}
Upvotes: 0
Reputation: 16550
the 'tr' program, which would have to be executed from the shell (or by calling system()
from a C program) would do it easily.
Upvotes: -1
Reputation: 10123
Prefer to use letter literals over numeric:
if (a[i] >= 'a' and a[i] <= 'z')
Watch your flow. Currently you have
if (is lower) ...
else b[i] = something;
if (is upper) ...
else b[i] = something;
You can combine that into a single if and avoid repeating stuff:
if (is lower) b[i] = ...
else if (is upper) b[i] = ...
else b[i] = ...
If you are permitted, you can also determine a character’s class by #including and using isupper()
and islower()
.
Finally, you can use some modular arithmetic to simplify your expressions.
b[i] = ((a[i] - 'a') + shift) % 26 + 'a';
Personally, I'd write a function to do this:
char shift( char c, int shift )
With said function, you can have a very pretty if statement...
:O)
Upvotes: 2