reverse the string

Recommended Answers

All 7 Replies

are you allowed to use another char array to save the reversed string? If you are, then start at the end of the original string and work backwards towards the first character, in the loop store each character in the second array from front to last.

For example, if the string is "abc" then start with the last character which is 'c', copy it to the first byte of another string.

There are several ways to accomplish that, but the simplest is probably calling strlen() to get the length of the original string, then a for loop to count from whatever that returns to 0.

for(int i = len; i >= 0; --i)

Minor issue AD. You are starting at the terminating null byte and then ending at the head of the string. Better this I think:

for(int i = len-1, j = 0; i >= 0; --i, ++j)
    target[j] = source[i];
target[len] = 0; // Properly terminate the target string.

The question does not seem to preclude the use of a human processor so how about

#include <string>
#include <iostream>

int main()
  std::string text;
  std::string reversed;

  std::cout << "Please enter the string to reverse: " << std::flush;
  std::getline(std::cin, text);
  std::cout << std::endl;

  std::cout << "Please enter the reverse of \"" << text << "\": " << std::flush;
  std::getline(std::cin, reversed);
  std::cout << std::endl << std::endl;

  std::cout << "The reverse of \"" << text << "\" is \"" << reversed << "\"." << std::endl;

  return 0;

And let us not forget it does preclude any library so you could just std::reverse(text.begin(), text.end()); :D

commented: Great post Banfa! Nothing like leveraging stuff like the STL. +12

Another option...

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

char* reverse_string(char* str)
    for(int beg = 0,  end = strlen(str) - 1; beg < end; ++beg, --end)
        str[beg] ^= str[end];
        str[end] ^= str[beg];
        str[beg] ^= str[end];
    return str;

int main(void)
    char buffer[]="Hello World";
    printf("%s\n", reverse_string(buffer));
    return 0;

As long as we're giving all sorts of answers, how about

for(int i = 0, j = len-1; i < len/2; i++, j--)
    temp = str[i];
    str[i] = str[j];
    str[j] = temp;

or even shorter:

for (int i = 0; i < strlen(str) / 2; ++i){
    char t = str[i];
    str[i] = str[strlen(str)-1-i];
    str[strlen(str)-1-i] = t;

why are you calling strlen() so many times? Do you expect the length of the string to change?

int length = strlen(str);
for (int i = 0; i < length / 2; ++i){
    char t = str[i];
    int x = length - 1 - i;
    str[i] = str[x];
    str[x] = t;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.