简体   繁体   中英

Reverse string with pointers in C

I tried following two ways to reverse a string in C using char pointers:

Option 1:

void stringreverse(char *s){
    int n = stringlength(s) - 2;

    while(*s != '\0'){
        char c = *s;
        *s = *(s+n);
        *(s+n) = c;
        s++;n--;
    }       
}

Option 2:

void stringreverse(char *s){
    char *p = s + stringlength(s) - 2;

    while(*s != '\0'){
        char c = *s;
        *s = *p;
        *p = c;
        s++,p--;
    }   
}

None of the above works. Hints on why?

The problem is that your code reverses the string and then reverse it again, because your loop goes from 0 to len (when *s==\\0), it should stop at (len-1)/2

You should try this :

void stringreverse(char* s){
  int len = strlen(s)-1;
  int i;
  for(i=0;i<len/2;i++){
    char tmp = s[i];
    s[i] = s[len-i];
    s[len-i]=tmp;
  }
}

To reverse the string you should swap the chars between the beginning and the end of the string until they meet in the middle, the way you did will reverse it and then reverse it again to the original string. Also there is strlen in standard C. Anyway using your definition of stringlength , it should be:

void stringreverse(char *s){
    int n = stringlength(s) - 2;
    int i;
    while(i = 0; i < n / 2; i++) {
        char c = s[i];
        s[i] = s[n-i];
        s[n-i] = c;
    }       
}

complete working sample using pointers:

#include <stdio.h>    
void reverse(char *p){
    char c;
    char* q = p;
    while (*q) q++;
    q--; // point to the end
    while (p < q){
        c = *p;
        *p++ = *q;
        *q-- = c;
    }
}

int main(){
    char s[] = "DCBA";
    reverse(s);
    printf("%s\n", s); // ABCD
}

p: points to start of string.
q: points to the end of string.
then swap their contents.
simple and easy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM