Translate

Saturday 26 May 2012

Strings in C++


      A string is a collection of character such as numeric digits alphabets or special characters enclosed within double quotes.
Single character constant can be used in arithmetic expressions whereas string constants cannot be used with arithmetic operations as shown below.
‘A’+3 = ‘D’  or 68   but   “A”+3= Invalid

Declaration:- A string variable is an array variable of type character. It can be declared as shown.
char a[80]

Initialization:- Like integer arrays initialized with some values, an array variable declared as a type of character can be initialized with an aray of characters or string.
char sn[7]= {'a', 'c', 'd', '-', '4', '0', '\0'};
      Thus null character ‘\0’ has to be included when the initialization is carried out with a list of characters. The system assigns a null character when a string variable is initialized with a string constant. Every string is terminated by a null character.

Q. Write a program to read a string and count number of alphabets digits and special characters used in it.
#include <iostream>
void main()
{
    char st[100];
    int i, ca=0, cd=0, csp=0;
    cout<< “Enter a string \n”;
    gets(st);
    for(i=0; st[i]!=‘\0’; i++)
    if (st[i]> ‘a’ && st[i]< ‘z’ || st[i]> ‘A’ && st[i]< ‘Z’)
        ca++;
    else if (st[i]> ‘0’ && st[i]<’9’)
        cd++;
    else
        csp++;
    cout<< “No of alphabets= ”<< ca << endl 
        << “No of digits= ”<< cd<<endl
        <<”No of special characters=”<<csp;
}

1 comment:

  1. Variables in programming languages ​​practically do not differ much except the method of writing them in the code. It's great that you can now have many applications there about cloud integration and there is no problem. Therefore, I am of the opinion that all applications that work in the cloud are future-proof.

    ReplyDelete

Total Pageviews