简体   繁体   中英

Reversing a string in C using a for loop?

Ive been trying to reverse a string as simply as possible , trying to prove a point to myself but for some reason the code is not working. I know i can easily find a different approach online but then i wont learn anything. So would anyone explain please?

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

int main()
{   int i,n,c=0;
    char s[50];
    char a[50];
    for(i = 0; i < 50;i++)
        scanf("%[^\n]c",&s[i]);
    for(n = strlen(s), i = 0; n > i; n--,c++)
        s[c] = s[n-1];

    printf("%s", s);
    return 0;
}

For starters you need to include the header <string.h> .

This loop

for(i = 0; i < 50;i++)
    scanf("%[^\n]c",&s[i]);

does not make a great sense. Moreover you need to append the entered string with the terminating zero character '\\0' .

What you need is to enter a string one time as for example

scanf("%49s", s );

Or even better to write

scanf( "%49[^\n]", s );

to enter a string with several words in the array.

This for loop

for(n = strlen(s), i = 0; n > i; n--,c++)
    s[c] = s[n-1];

also does not make a sense. It does not reverse the string. The variable i is not increased. That is you need to swap two characters.

Also you need to declare variables in minimum scopes where they are used.

The loop can look for example the following way

for ( size_t i = 0, n = strlen(s); i < n / 2; i++ )
{
    char c = s[i];
    s[i] = s[n-1-i];
    s[n-1-i] = c;
}

Apart from all these the declared array a is not used in the program.

So the program can look the following way

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

int main( void )
{
    char s[50] = "";
 
    scanf( "%49[^\n]", s );

    for ( size_t i = 0, n = strlen(s); i < n / 2; i++ )
    {
        char c = s[i];
        s[i] = s[n-1-i];
        s[n-1-i] = c;
    }

    puts( s );
}

If to enter string

Hello, unikatura!

then the program output will be

!arutakinu ,olleH
  1. Use functions.

Two variants:

char *reverse(char *str)
{
    char *end = str, *start = str;

    if(str && *str)
    {
        for(;*(end + 1);end++);
        for(;end > start;)
        {
            char tmp = *end;
            *end-- = *start;
            *start++ = tmp;
        }
    }
    return str;
}


char *reverse1(char *dest, const char *str)
{
    char *wrk = dest;
    size_t len = 0;

    if(str)
    {
        for(;*str;len++, str++);str -= !!*str;
        for(;len--; *wrk++ = *str--);
    }
    *wrk = 0;
    return dest;
}

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