![]() |
|
[C++] String Reversion using Pointers! - Printable Version +- Sinisterly (https://sinister.ly) +-- Forum: Coding (https://sinister.ly/Forum-Coding) +--- Forum: Coding (https://sinister.ly/Forum-Coding--71) +--- Thread: [C++] String Reversion using Pointers! (/Thread-C-String-Reversion-using-Pointers) |
[C++] String Reversion using Pointers! - Iyyel - 06-07-2015 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 : !olleHAnd 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.
RE: [C++] String Reversion using Pointers! - CoolixHD - 06-07-2015 Very nice tutorial, Iyyel! Keep up the good work.
RE: [C++] String Reversion using Pointers! - Zodiac - 06-07-2015 Thanks for sharing this mate!
RE: [C++] String Reversion using Pointers! - bitm0de - 07-29-2015 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: tring and iterators instead of pointers.
|