Login Register


[C++] String Reversion using Pointers! filter_list
Author
Message
[C++] String Reversion using Pointers! #1
Hello there guys!

So a little introduction about myself before I start to show you anything. I have been doing Java (on & off) for a few years now, and I recently started discovering the world of C++, and I must say I love it a lot. So here I am with a little tutorial/showcase on how to reverse a string or array of characters in C++ by the use of pointers.

Code:
#include <iostream> int main(int argc, char *argv[]) { char text_array[] = "Hello!"; int text_array_len = (sizeof(text_array) - 1); std::cout << "Char Array Len: " << text_array_len << std::endl; char *p_start = &text_array[0]; std::cout << "Array Start: " << *p_start << std::endl; char *p_end = (text_array + text_array_len) - 1; std::cout << "Array End: " << *p_end << std::endl; std::cout << "Before: " << text_array << std::endl; while (p_start < p_end) { char save = *p_start; *p_start = *p_end; *p_end = save; p_start++; p_end--; } std::cout << "After : " <<  text_array << std::endl; return 0; }

A little explanation for my code. I take two integer pointers, pointing to the start character and end character of the array, as well as an integer that stores the length of characters in the array. I then use a while loop (you can use a for loop as well, this is just how I do it) to iterate through the array, essentially swapping the individual characters with each other.

Code:
Char Array Len: 6 Array Start: H Array End: ! Before: Hello! After : !olleH

And this is the output! As I said before, this is just how I do it. It works with single characters such as 'a' or 'b' as well with long arrays of characters. I hope this will be useful for at least someone!

Thanks for reading!

Iyyel.
[Image: Tbv8oDu.png]

Reply

RE: [C++] String Reversion using Pointers! #2
Very nice tutorial, Iyyel! Keep up the good work. Smile

Reply

RE: [C++] String Reversion using Pointers! #3
Thanks for sharing this mate! Smile

Reply

RE: [C++] String Reversion using Pointers! #4
Here's my version:
Code:
char *reverse_string(char *src) { if (!src || !*src) return src; char *p_beg = src; char *p = src; while (*(p + 1)) ++p; while (p > p_beg) { char tmp = *p; *p-- = *p_beg; *p_beg++ = tmp; } return src; }

And just so you know, this is not the C++ way of going about reversing a string. C++ programmers rarely use (raw) pointers, and you would probably see an implementation using std:Confusedtring and iterators instead of pointers.
- mostly braindead monkeys on this forum.

Reply







Users browsing this thread: