Advertisement
Shaun_B

Reversing a string in C

Jan 31st, 2012
438
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.03 KB | None | 0 0
  1. /** A bit of code which will ask you to enter a string and then it'll
  2.  *  write it in reverse. MMXII Donkeysoft */
  3. // Unfortunately, I used Visual Studio 2010, so you need to add the following
  4. // in place of this, or in the StdFxa.cpp file:
  5. // #include <stdio.h>
  6. // #include <stdlib.h>
  7. // #include <conio.h>
  8. // #include <string.h>
  9. #include "stdafx.h"
  10. // Function prototypes:
  11. void main (void);
  12. void clear (void);
  13. static void reverse (void);
  14. // Global variables:
  15. static int i=0;
  16. static int count=0;
  17. static char word[255];
  18. static char reversed[255];
  19. static int nChars;
  20. static char key=' ';
  21. void main(void)
  22. {
  23.      // Does a cheat for clearing the console:
  24.      clear();
  25.      printf("Enter a word or sentence to be reversed (max is 255 characters): ");
  26.      scanf("%s", word);
  27.      printf("\n");
  28.      // Calls the function to reverse the string:
  29.      reverse();
  30.      i=0;
  31.      // Writes each character while not null:
  32.      while(word[i])
  33.      {
  34.           printf("%c",word[i]);
  35.           i=i+1;
  36.      }
  37.      printf(" reversed is %s\n",reversed);
  38.      printf("\nPress any key to exit.");
  39.      // Sets key to zero:
  40.      key=0;
  41.      // Repeats until a key is pressed, or in other words, waits until a key is pressed:
  42.      while(!key)
  43.      {
  44.           key=getchar();
  45.      }
  46. }
  47. // Clear console function:
  48. void clear(void)
  49. {
  50.      // 120 newlines:
  51.      for(i=0;i<120;i=i+1)
  52.      {
  53.           printf("\n");
  54.      }
  55. }
  56. // Reverse function:
  57. void reverse(void)
  58. {
  59.      nChars=0;
  60.      // Counts number of characters:
  61.      while(word[nChars])
  62.      {
  63.           nChars=nChars+1;
  64.      }
  65.      printf("Word length is %d\n",nChars);
  66.      // The last character is null, so we don't need that:
  67.      nChars=nChars-1;
  68.      // Writes the indexed string at reversed [0+i] to the indexed string word [char-i]
  69.      for(i=0; i<=nChars+1; i=i+1)
  70.      {
  71.           reversed[i]=word[nChars-i];
  72.      }
  73.      // Adds a null value to say that this is the end of the string:
  74.      reversed[i]='\0';
  75.      // Should clear keyboard buffer:
  76.      getchar();
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement