Program to Reverse String C++

In this post we are going to create a program to reverse string in C++ programming language.

Reversing a number is quite easy task, see this to reverse a number

Program to reverse a number

Logic to Reverse a String:

To reverse a String we just exchange the first character with last character till we reach the mid of the string.

suppose we have a string ‘PROPROGRAMMING’, let’s see the steps:

  • We have 2 for loops, one from starting from 0 position and other starting from last position
  • Now we swap first value with last i.e. P will be swapped with G
  • Now first loop goes to position 0 + 1, and second loop goes to last – 1 position.
  • Now these values are swapped i.e. R with N
  • We continue to do this step till we reach the mid of the string.
  • Finally we have ‘GNIMMARGORPORP’

 

Program to Reverse String C++:

#include<iostream>
using namespace std;

int main( )
{
    int l,i,j;
    char str[80];
    int temp;
    cout<<"Enter string :";
    gets(str);

    for(l=0;str[l]!='';l++);    //finding length of string

    for(i=0,j=l-1;i<l/2;i++,j--)
    {
        temp=str[i];
        str[i]=str[j];
        str[j]=temp;
    }

    cout<<"Reverse String isn"<<str;

    return 0;
}

 

OUTPUT:

reverse string c++

Program to check whether String is palindrome or not C++

A simple program to check whether String is palindrome or not C++

PROGRAM:

#include<iostream>
using namespace std;

int main( )
{
    int L,C;
    char str[80];
    cout<<"nEnter a string: ";
    gets(str);

    for(L=0;str[L]!='';L++);      //To find length of the string

    for(C=0;(C<L/2) && (str[C]==str[L-C-1]);C++);

    if(C==L/2)
        cout<<"ntString is Palindrome";
    else
        cout<<"ntNot a palindrome";
    return 0;
}

 

OUTPUT:

string is palindrome or not c++

Program to Find length of String C++

This is a simple program to find Length of a String in C++.

Just traverse the string till NULL (‘’), increment the ‘i’ likewise.

Program to Find length of a String C++

#include<iostream>
using namespace std;

int main( )
{
    int i;
    char str[80];
    cout<<"Enter a string:";
    gets(str);

    for(i=0;str[i]!='';i++);

    cout<<"Lenght of string is :"<<i;

    return 0;
}

 

OUTPUT:

length of string in C++

C++ Program to Count number of Words in String

PROGRAM:

#include<iostream>
using namespace std;

int main()
{

char str[100];
int w=1;
cout<<"Please enter a String: ";
gets(str);

for (int i=0;str[i]!='';i++)
{
if(str[i]==' ')
w++;
}
cout<<"There are "<<w<<" words.";
return 0;
}

 

OUTPUT:

count words in string