Last active
September 7, 2018 17:14
-
-
Save EdgeCaseBerg/5931519 to your computer and use it in GitHub Desktop.
Exercise 1-19 from The C Programming Language by Brian W. Kernighan, Dennis M. Ritchie. "Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input line by line" Only instead of a function I've written a small program that accepts piped in input and does it there
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define MAXLENGTH 1000 | |
//Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input line by line | |
void reverse(char s[], int lim){ | |
int i,j; | |
j=lim-1; | |
i=0; | |
while(i < j){ | |
//XOR Swap algorithm to save space and for efficiency | |
s[i] ^= s[j]; | |
s[j] ^= s[i]; | |
s[i] ^= s[j]; | |
++i; --j; | |
} | |
} | |
int ourgetline(char s[], int lim){ | |
int c,i; | |
for(i=0; i < lim-1 && (c=getchar()) != EOF && c != '\n'; ++i) | |
s[i] = c; | |
if(c == '\n'){ | |
s[i] = c; | |
++i; | |
} | |
s[i] = '\0'; | |
return i; | |
} | |
main(){ | |
char in[MAXLENGTH]; | |
int len; | |
len=0; | |
while((len = ourgetline(in,MAXLENGTH)) > 0){ | |
reverse(in,len); | |
printf("%s", in); | |
} | |
} |
include <stdio.h>
define MAXLENGTH 1000
//Write a function reverse(s) that reverses the character string s. Use it to write a program that reverses its input line by line
void reverse(char s[], int lim){
int i,j;
j=lim-1;
i=0;
while(i < j){
//XOR Swap algorithm to save space and for efficiency
s[i] ^= s[j];
s[j] ^= s[i];
s[i] ^= s[j];
++i; --j;
}
}
int ourgetline(char s[], int lim){
int c,i;
for(i=0; i < lim-1 && (c=getchar()) != EOF && c != '\n'; ++i)
s[i] = c;
if(c == '\n'){
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
void main(){
char in[MAXLENGTH];
int len;
len=0;
while((len = ourgetline(in,MAXLENGTH)) > 1)//replace 0 with 1 so that program can terminate
{
reverse(in,len);
printf("%s", in);
}
}
#include <stdio.h>
#include <string.h>
int main(){
char *name = "Santee" ;
int len = strlen(name) ;
name += len ;
while (len--)
printf("%c", *--name) ;
return 0 ;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: