Sunday 29 June 2014

C++ program to reverse a string

Here is C++ program to reverse a string without using strrev(),using swapping, using pointer, using strrev() function, using recursion.


Method 1 : C++ program to reverse a string without using strrev()
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
    char temp[50],str[50];
    int len;
    cout<<"Enter String : ";
    cin>>str;
    len=strlen(str)-1;
    for(int y=0;y<=len;y++)
         temp[len-y]=str[y];
    for(int y=0;y<=len;y++)
        str[y]=temp[y];
    cout<<"Reverse of string is : "<<str;
    return 0;
}



Method 2 : C++ program to reverse a string using swapping function
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
    char temp,str[50];
    int i;
    cout<<"Enter String : ";
    cin>>str;
    i=strlen(str)-1;
    for(int y=0;y<i;y++,i--)
    {
        temp=str[i];
        str[i]=str[y];
        str[y]=temp;
    }
    cout<<"Reverse of string is : "<<str;
    return 0;
}



Method 3 : C++ program to reverse a string using strrev function
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
    char temp,str[50];
    cout<<"Enter String : ";
    cin>>str;
    strrev(str);
    cout<<"Reverse of string is : "<<str;
    return 0;
}



Method 4 : C++ program to reverse a string using pointer
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char *p,*q,str1[20],temp;
    int res;
    cout<<"Enter String : ";
    cin>>str1;
    p=str1;
    res=strlen(str1)-1;
    q=str1+res;
    res/=2;
    for(int y=0;y<res;y++,p++,q--)
    {
        temp=*p;
        *p=*q;
        *q=temp;
    }
    cout<<"Reverse of string is "<<str1;
    return 0;
}




Method 5 : C++ program to print reverse of a string using recursion
#include<iostream>
using namespace std;
void restr(char *str,int i)
{
    if(str[i]=='\0')
        return ;
    else
        restr(str,i+1);
    cout<<str[i];
}
int main()
{
    char str[50];
    cout<<"Enter string : ";
    cin>>str;
    cout<<"Reverse of string : ";
    restr(str,0);
    return 0;
}




No comments:

Post a Comment