Friday 8 November 2013

Number of characters in a string - C++ Program Source Code!

This program is to count the number of spaces in an input string.

Here is the code:
#include<iostream.h>
#include<conio.h>

void main()
{

int spaces, i;
char str[100];
int spaces = 0;

cout<<"Enter the string!"<<endl;
cin.getline(str, 100);
cout<<"Entered string is \'"<<str<<"\'"<<endl;

for(i=0;i<=100;i++)
{
 if (str[i] == ' ')
 {
  spaces = spaces + 1;
 }
}
cout<<"There are "<<spaces<<" spaces in the given string!"<<endl;
}

For newer IDEs (like Dev C++):
#include<iostream>
using namespace std;
void main()
{
   int spaces, i;
   char str[100];
   int spaces = 0;
   cout<<"Enter the string!"<<endl;
   cin.getline(str, 100);
   cout<<"Entered string is \'"<<str<<"\'"<<endl;
   for(i=0;i<=100;i++)
   {
      if (str[i] == ' ')
      {
         spaces = spaces + 1;
      }
   }
   cout<<"There are "<<spaces<<" spaces in the given string!"<<endl;
   return 0;
}


Working:
Here we use the concept 'String, basically is an array!'. First we input the string str. Let spaces be the number of spaces in the string. Initially it is set to 0. We are going to loop through the string (array), and if any of the element in that array is found to be ' ', or a space, spaces is incremented by 1. By the end, the spaces is going to be the total number of spaces in the string. 

No comments:

Post a Comment

You might also like