Skip to content

Instantly share code, notes, and snippets.

@EdgeCaseBerg
Last active September 7, 2018 17:14
Show Gist options
  • Save EdgeCaseBerg/5931519 to your computer and use it in GitHub Desktop.
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
#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);
}
}
@EdgeCaseBerg
Copy link
Author

Usage:

$ cc reverse.c -o reverse
$ ./reverse < filetoreverse.txt > output.txt

@vitthal8rv7
Copy link

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);
}

}

@sbalasa
Copy link

sbalasa commented Sep 7, 2018

#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