Software & Finance





C Programming (Turbo C++ Compiler) Loops - Reverse a String With Out Using String Library Functions





I have used while loop to find out the length of the string and for loop to reverse the string. The function name is ReverseString which does the work for you.


Source Code


bool ReverseString(const char *src, char *dst, int len)

{

    const char *p = src;

 

    // count the length

    int count = 0;

    int i = 0, j = 0, k = 0;

    while(1)

    {

        if(p == NULL || *p == '\0' ||

            *p == '\t' || *p =='\n' || *p == '\r')

        {

            count = i;

            break;

        }

        p = p + 1;

        i = i + 1;

    }

 

    if(count > len)

    {

        return false; // Insufficient memory in the destination pointer

    }

 

    for(j = count - 1; j >= 0; j--)

    {

        dst[k++] = src[j];

    }

    dst[k] = '\0';

 

    return true;

}

 

 

int main()

{

 

    char src[] = "Kathir";

    char dst[32];

    ReverseString(src, dst, 32);

    printf("%s\n%s\n", src, dst );

    return 0;

}

Output


Kathir
rihtaK