Reverses the character string s. - C String

C examples for String:char array

Description

Reverses the character string s.

Demo Code

#include <stdio.h>

#define MAXLINE 1000/*from   www .  j  av  a 2s . c o  m*/

void reverse(char s[]);

int main(void){
    char line[MAXLINE] = "this is a test";

    reverse(line);
    printf("%s\n", line);
    return 0;
}

void reverse(char s[]){
    int i, j;
    int tmp;

    for (j = 0; s[j] != '\0'; ++j)
        ;
    --j;
    if (s[j - 1] == '\n')
        --j;

    for (i = 0; i < j; ++i, --j) {
        tmp = s[i];
        s[i] = s[j];
        s[j] = tmp;
    }
}

Result


Related Tutorials