-
Returning a string
I need to reverse a string and display the original using one function. I have the function to reverse it, but i dont know how to display the original one. Any help would be appreciated.
Code i have so far:
Code:
#include <string.h>
#include <stdio.h>
#define CAPACITY 35
void reverseString(char *str)
int main (void)
{
char first[CAPACITY];
char last[CAPACITY];
printf(" Enter your first and last name: ");
scanf("%s %s", first, last);
reverseString(first, first);
reverseString(last, last);
printf("The reverse of your name is: %s,%s \n", first, last);
}
void reverseString(char *str)
{
char *p = str;
char *q = str + strlen(str) - 1;
char temp;
while(p<q)
{
temp = *p;
*p = *q;
*q = temp;
++p;
--q;
}
}
-
Your function works by overwriting the original string, so before calling your function you can either:
1) print the original string
2) make a copy of the original string to print later (see strcpy() in strings.h)
-
Code:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
static char *rev(char *to, const char *from)
{
const char *endp = from + strlen(from);
char *save = to;
while (endp > from)
*to++ = *--endp;
*to = '\0';
return save;
}
static int read(char *to, size_t n)
{
int c;
n--;
while ((c = getchar()) != EOF && !isspace(c))
if (n) {
*to++ = c;
n--;
}
*to = '\0';
return c;
}
int main(void)
{
char first[35], last[35];
char rfirst[sizeof first], rlast[sizeof last];
while (read(first, sizeof first) != EOF
&& read(last, sizeof last) != EOF)
printf("%s %s\n", rev(rfirst, first), rev(rlast, last));
return 0;
}