reverse a string using pointers

28,464
inline void swap(char* a, char* b)
{
    char tmp = *a;
    *a = *b;
    *b = tmp;
}

inline void reverse_string(char* pstart, char* pend)
{
    while(pstart < pend)
    {
        swap(pstart++, pend--);
    }

}

int main()
{
    char pstring[] = "asfasd Lucy Beverman";
    auto pstart = std::begin(pstring);
    auto pend = std::end(pstring);
    pend -= 2; // end points 1 past the null character, so have to go back 2
    std::cout << pstring << std::endl;        
    reverse_string(pstart, pend);
    std::cout << pstring << std::endl;
    return 0;
}
Share:
28,464
user2420395
Author by

user2420395

Updated on July 09, 2022

Comments

  • user2420395
    user2420395 almost 2 years

    I have to admit, i have no idea how to use pointers, but I tried non the less. the problem with my program is that it shows the string in reverse, except for what was the first letter being missing and the entire string is moved one space forward with the first element being blank. for example it show " olle" when typing "hello".

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    string reverse(string word);
    
    int main()
    {
    char Cstring[50];
    cout<<"enter a word: ";
    cin>>Cstring;
    string results = reverse(Cstring);
    cout <<results;
    }
    
    string reverse(string word)
    {
        char *front;
        char *rear;
        for (int i=0;i< (word.length()/2);i++)
        {
                front[0]=word[i];
                rear[0]=word[word.length()-i];
                word[i]=*rear;
                word[word.length()-i]=*front;
        }
        return word;
    }
    

    The new code works perfectly. changed the strings to cstrings. the question technicaly asked for cstrings but i find strings easier so i work with strings then make the necesary changes to make it c string. figured out ho to initialize the rear and front as well.

    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    string reverse(char word[20]);
    
    int main()
    {
    char Cstring[20];
    cout<<"enter a word: ";
    cin>>Cstring;
    string results = reverse(Cstring);
    cout <<results;
    }
    
    string reverse(char word[20])
    {
        char a='a';
        char b='b';
        char *front=&a;
        char *rear=&b;
        for (int i=0;i< (strlen(word)/2);i++)
        {
                front[0]=word[i];
                rear[0]=word[strlen(word)-1-i];
                word[i]=*rear;
                word[strlen(word)-1-i]=*front;
        }
        return word;
    }