String Handling in C++

 C++ Strings

String

  • It is a set of characters (group of characters) arranged in sequential memory location

  • In c/c++, there is no specific built-in data type point to string type 

  • We can perform various operations on strings such as

    • Comparing

    • Joining

    • Reversing

    • Indexing and many more, etc,... 

  • C++ supports two types of strings. They are

    • C Style String (Character Array)

    • String Class.

1. C STYLE STRING

  • In c style string, the string is group of characters terminated with null character

  • It will be created either character array or character pointer

Example 1 – String Declaration

     char name[50];

Example 2 – String Definition

     char name[]=”Hello”;

  • Here, the array name will hold the values “Hello” with additional null character \0 which is automatically added by the compiler (unlike c)

Memory Representation

    

I. EXAMPLE OF C STYLE STRING

1. SOURCE CODE

#include <iostream>

using namespace std;

int main()

{

    cout<<"----------------------------------------\n";

cout<<"\t Character String\n";

    cout<<"----------------------------------------\n";

// string definition using c style

char name[]="Hello World";

    cout<<name<<"\n";

return 0;

}

2. OUTPUT

DIFFERENCE BETWEEN C STRING AND STRING CLASS IN C++

S.N

C STRINGS

STRING CLASS

1.

It is statically allocated

It is dynamically allocated

2.

It can be created using character array

It can be created using the predefined class string

3.

Access speed is fast

Access speed is slow

4.

Syntax:

string variable-name;

Syntax:

   char variable-name[size];

5.

Example:

char a[100];

Example:

string obj;


Comments

Popular posts from this blog

Vivo V30 Pro 5G

Xiaomi 14 - Features, Price

Oppo F25 Pro 5G Review - Features, Price