on Leave a Comment

C++ String - String Class and Char Array

In C++, strings can be represented in two ways.

(1) String using char array (C style string)

(2) String class

C++ String Using Char Array

String is also known as character array. A collection of character is string. String can be used to manipulate words and sentences.

A string constant is one-dimensional array of character and each array is terminated by null ('\0=0').

We know that a character occupies 1 byte. '\0' is null character and it is only one character and its ASCII value is '0'.

To manipulate string using char array, you must include string.h header file.

Defining a String Using Char Array

Examples:

char s[] = ('P','R','O','G','R','A','M','M','I','N','G','\0');

char s[] = "PROGRAMMING";

char s[12] = "PROGRAMMING" ;

Function in string.h header file

There are many functions in string.h header file to manipulate strings. Some of them are:

strlen : Find length of string .

strcat : Appends one string at the end of other string. Concatenate two strings.

strcmp : Compares two strings.

strrev : Reverse a string.

strcpy : Copy one string to another.

strlwr : Convert a string to lowercase.

strupr : Convert a string to uppercase.


String Class

We have learnt above about string using char array or c style string. ANSI standard C++ provides a new class called string. We can make string objects using string class.

To using string class, we must include this statement,
#include<string>

String class has many methods, constructors and operators to manipulate string object.

Declaring a String Object

A string object can declared in the same way as declaring other objects. 

string str;

Initializing a String Object

Using one argument constructor
string str("PC TECHNICAL PRO");

By simply assigning string
string str="PC TECHNICAL PRO";

Functions of String Class

String class has many functions or methods to manipulate string object.

Some of them are : 

append() : Appends a string to other string.

empty() : Check whether a string is empty or not. If string is empty, returns one, else return 0.

length() : calculates the length of string.

Operators of String Class

String class has many overloaded operators to manipulate string object.

Some of them are : 

=        Assigning values to strings object. We can assign one string to other string object using (=) operator.

+       Concatenation

==        Check whether two string objects are equal.


0 comments:

Post a Comment