facebook like button

10 April, 2011

program 31: reversing a string


The need:
     This program in some places we need to reverse the given string like in next post (binary conversion). This program asks the user for a string, reverses that and prints back.

The code: 
--------------------------------------------
#include<stdio.h>
#include<string.h>
main()
{
    int i=0,length;
    char c,str[50];
    printf("Enter a string => ");
    gets(str);
    length=strlen(str);
    for(i=0;i<length/2;i++)
    {
      c=str[i];
      str[i]= str[length-1-i];
      str[length-1-i]=c;
    }
    printf("\nreversed string is => ");
    puts(str);
    getchar();
}
--------------------------------------------
 
The approach:     
    There are many ways to reverse a string. Here I have exchanged last character with first, second with second last and so on up to middle of string.

2 comments:

  1. Hello Sir,

    I am trying to print a string without the spaces but the output i get is only the first word of the string i enter.Can you please point out the flaw in my code

    #include
    int main()
    {
    char a[100],b[100];
    printf("enter any string \n");
    scanf("%s",a);
    int i=0;
    while (a[i]!='\0')
    {
    if(a[i]!=' ')
    b[i]=a[i];
    i++;
    }
    b[i]='\0';
    printf("string without spaces : %s \n",b);
    return 0;
    }

    Thank you

    ReplyDelete
    Replies
    1. you need to know one thing about string(character array) in C which is: "the '\0' or NULL character is used to indicate end of the string."
      Hence the flaw is:
      you are replacing all ' ' with '\0' which is replaced successfully in the memory but when it comes to printing program starts to print the string character by character. When the first word finishes there it finds '\0' in your case. It assumes string end and stops further printing.

      further tip:
      To remove spaces in addition to 'i' use one more counter say 'j' and do not replace ' ' with '\0' just skip copying it.

      Delete

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply