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





Messages In This Thread
[C++] String Reversion using Pointers! - by Iyyel - 06-07-2015, 11:29 AM



Users browsing this thread: