how to write a program in c++ to combine two strings and another to reverse the string

Hello Eddie, thanks for the question.

This isn't all that hard of a task thanks to a function called "strcat" which resides in string.h. It appends one string to another. Lets look at how you could combine 2 strings:

// in main

char *one = "Hello", *two = " World";

char result[64] = {0};

strcat(result, one);

strcat(result, two);

cout << result << '\n';

And we have concatonated the strings together. To reverse a string is a little bit more tricky. For simplicity's sake, lets reverse the string we just made:

// in main after the code above

char *r = new char[strlen(result) + 1];

r[strlen(result)] = '\0';

int count = 0;

for(int i = (int)strlen(result) - 1; i >= 0; i--)
      r[count++] = result[i];

cout << r << '\n';

delete [] r;

Notice we dynamically allocate as much space as needed + 1 extra char for the NULL terminator, which we then set. Then in the for-loop we loop through the string backwards, skipping the first backwards char which is the NULL terminator. We print out the string via cout, then clean up the memory we allocated with delete.

I hope this information was helpful.

- Eddie


All Answers

Answers by Expert:

Ask Experts




I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.


I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2017 About.com. All rights reserved.