Reverse 字符串

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void reverseString(char str[]);
void exchange(char *a, char *b);

int main(int argc, char *argv[])
{
    //char x = 'a';
    //char y = 'b';
    char string[100];
    if(argc == 1)
    {
        fprintf(stderr, "No string!\n");
        exit(-1);
    }
    //printf("%c %c\n", x, y);
    //exchange(&x, &y);
    //printf("%c %c\n", x, y);
    strcpy(string, argv[1]);
    reverseString(string);
    printf("\nReversed string: %s\n", string);
    return 0;
}

void reverseString(char str[])
{
    int length;
    int i, j;
    //length = sizeof(str) / sizeof(str[0]);
    length = strlen(str);//number of char in a string exclude '\0'
    //printf("length: %d\n", sizeof(str) ); //here sizeof(str) return length of pointer str, namely 4
    i = 0;
    /*start from first and last char of a string*/
    while(i < length/2)
    {
        exchange(&str[i], &str[length-1-i]);
        i++;
    }
}

/*change value of a and b*/
void exchange(char *a, char *b)
{
    char temp;
    temp = *a;
    *a = *b;
    *b = temp;
}


你可能感兴趣的:(c,String,Exchange)