Some friend of mine just asked me to write him a simple string inverter in C, meaning a little program which reads a string and outputs the same string in inverted order. For example:
Input: Hello, we are done!
Output: !enod era ew ,olleH
I honestly don’t know the use of it, but any way here is it. (Not tested, but it should work fine)
Read more to see the code or download it zipped.
I just wrote a quick & dirty PHP version as well. Download.
However, the PHP version could be simplified a lot (one line of code):
<?php
echo strrev("Hello, we are done!");
?>
Here’s the C code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct list
{
char item;
struct list *link;
};
typedef struct list x;
x *stack, *temp = NULL;
/* Pushes characters to the stack */
push(char data)
{
stack = (x *)malloc(sizeof(x));
stack->item = data;
stack->link = temp;
temp = stack;
}
/* Pops characters from the stack */
pop()
{
x *t;
while(temp != NULL)
{
printf("%c", temp->item);
t = temp;
temp = temp->link;
free(t);
}
printf(" ");
temp = NULL;
}
main()
{
int i;
char string[30];
clrscr();
printf("\n Your text: ");
gets(string);
i = 0;
printf("\n Inverted: ");
while(string[i] != '\0')
{
(isspace(string[i]) != 0) ? pop() : push(string[i]);
i++;
}
pop();
}