Home > OS >  Reversing a string on C language
Reversing a string on C language

Time:05-13

In this program, the user is allowed to enter words of up to 20 letters, which are stored in another array and printed from the end. But there is error on my code, the program output single letter after I enter a word. That is my code.

  #include <stdio.h>

  int main(void) {
      char user[21]; // created an array and let users enter letters
      char reverse[21]; // create an array and store the reverseing string
      printf("Please enter the word that you want to reverse: \n");
      scanf(" s",user);
      int length = sizeof(user) / sizeof(user[0]);
      int rever_index = 0;
      for (int i = 0; i < length; i  ) {
        reverse[i] = user[length-i];
        rever_index  ;
    }
      printf("reverse value are %s\n",reverse);
      return 0;
 }

Test result: Please enter the word that you want to reverse

string

reverse value are Z. How to modify my code?

CodePudding user response:

  1. For the length of the char array use strlen(user), because you already specify how many bytes the array gonna be (user[21]), and the compailer always is taking 21 bytes no matter how many chars you input. Also don't forget to #include <string.h> for strlen().
  2. In the for loop you need to use user[length-1-i], because indexes of array are from 0 to length-1. And when you try to access user[length], it's out of bounds.

(I tried to add this explanation in the comments up but I don't have enough reputation)

#include <stdio.h>
#include <string.h>
  int main(void) {
      char user[21]; // created an array and let users enter letters
      char reverse[21]; // create an array and store the reverseing string
      printf("Please enter the word that you want to reverse: \n");
      scanf(" s",user);
      int length = strlen(user);
      int rever_index=0;
      for (int i = 0; i < length; i  ) {
        reverse[i] = user[length-1-i];
        rever_index  ;
    }
      reverse[length] = '\0';
      printf("reverse value are %s\n",reverse);
      return 0;
 }

CodePudding user response:

There be dupes. But, just for fun, here's a bit of one liner.

/**
* Reverses a string
* @param str is the string to reverse.
* @returns a pointer to the resulting string
*/
char* rev(const char* str){

    // get length of string
    size_t len = strlen(str);

    // allocate a string of the appropriate size
    char* r = (char*)malloc(len);

    // work back down the string
    const char* s = str;
    for (; *s;   s) r[len - (s - str) - 1] = *s;

    return (r);

}
  •  Tags:  
  • c
  • Related