20130503

How to reverse a string using pointer or array in cpp without using strrev library function

How to reverse a string using pointer or array. CPP program for reversing a strings without using inbuilt library function strrev. How to reverse a sentence in cpp/C++/C without using library function strrev.Program to reverse a string using pointer.
#include<stdio.h>
#include<string.h>
int main()
{
char arr1[20];
printf("Enter a String:\n");
scanf("%s",&arr1);
printf("You entered:%s\n",arr1);



char arr2[20];

char *p1=arr1+strlen(arr1)-1;
char *p2=arr2;
while(p2<p1)
{
    *p2++=*p1--;
}
printf("You entered:%s\n",arr2);
return 0;
}
/*OUTPUT

 * Enter a String:
India
You entered:India
You entered:aidnI
*/


/*How to reverse a string without using library function strrev and strlen*/
#include<stdio.h>
#include<string.h>

void strRev(char *arr1);

int main()
{
char arr1[20];
printf("Enter a String:\n");
scanf("%s",&arr1);
printf("You entered:%s\n",arr1);

strRev(arr1);

return 0;
}
void strRev(char *arr1)
{
char *p1=arr1+strlen(arr1)-1;
char arr2[20];
char *p2=arr2;

while(p2<p1)
{
    *p2++=*p1--;
}
*p2='\0';

printf("Reverse String is:%s\n",arr2);
}

/*
Enter a String:
India
You entered:India
You entered:aidnI
*/

Previous             Home               Next

1 comment:

  1. cpp program to reverse a string using strrev
    #include
    using namespace std;
    #include
    int main()
    {
    char str1[]="howtocpp";
    strrev(str1);//strrev takes a string as parameter and reverse it.
    cout<<"Reversed is String is:"<<str1<<endl;
    return 0;
    }
    //OP:ppcotwoh

    ReplyDelete