String in reverse operation

String in reverse operation is one of the basic C programming language, discusses two ways here string in reverse:

1. Application of Space Law

#include "stdio.h"
#include "string.h"
#include "stdlib.h"

int main()
{
    char* src = "abcd";
    char* dest = NULL;
    int len = strlen(src);
    dest = (char*)malloc(len + 1);

    char* d = dest;
    char* s = &src[len - 1];

    while(len--)
    {
        *d++ = *s--;
    }

    *d = '\0';
    printf("%s\n", dest);
    free(dest);
    dest = NULL;

    return 0;
}

  

2, the internal substitution method

This method without additional application memory, and data cycles by half, more efficient

#include "stdio.h" 
#include "string.h" 

int main () 
{ 
    char the src [] = "ABCD"; 
    int len = strlen (the src); 
    int I = 0; 
    char TEMP; // temporary variables 

    for ( 0 = I; I <len / 2; I ++) 
    { 
        TEMP = src [I]; 
        src [I] = src [len - I -. 1]; // to be noted here, labeled 0 is the start of the array 
        src [ len - I -. 1] = TEMP; 
    } 

    the printf ( "% S \ n-", the src); 
    return 0; 
}

  

Guess you like

Origin www.cnblogs.com/xuyong437/p/11209124.html