Strings with string class declaration, initialisation and assignment – CSKC
Sign In

Search

Code Learning #CPP#3006    siteicon   siteicon  

Strings with string class declaration, initialisation and assignment

A program to demonstrate declaration and initialisation of strings in c++ using the string class.

Learning Objectives

  • Basic object declaration and initialisation of string class.
  • Learning to initialise a string in a function style manner.

Source Code

TC++ #3006

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Code Understanding

#include <string>
For all modern programming environments it is recommended to add this include line for using string class.

string s1;
string class instance s1 is declared here. It can be directly declared like a primitive data type. There is not need to define size of string. s1 is an object or instance of class string. It is treated like a variable only.Β The memory management is automatically done by c++ compiler, linker and runtime process.

s1=”C++ string class is easy to comprehend without a predefined size”;
It is very easy to comprehend. One can directly assign a string literal to a string class object. There is no need for giving any predefined size. This was not possible for null terminated strings as they were char arrays. This simple operation required strcpy() function earlier for null terminated strings.

cout<<s1<<endl;
This is direct printing of string class object like any other variable.

string s2=”Can be initialised by assignment”;
It can be initialised by direct assignment while declaration.

cout<<s2<<endl;Β //Printing of second string

string s3(“Initilisation like a function is also allowed”);
It can also be initialised in function style by enclosing the string literal within the parenthesis.

cout<<s3<<endl;Β  //Printing s3

 

Notes

  • Notice the use of #include <string>. It does not have a .h extension. The new set of header files in c++ do not have .h extension.
  • String class based strings also support null character within string. For. e.g.
    string s(“HAPY”,5); will have all 5 characters retained in string and
    cout<<s; will print HA PY.
    If the same is given as string string s(“HAPY”);Β then cout<<s; will print HA only


Suggested Filename(s): strclass.cpp



Share

Created: 25-Jan-2018 01:43 | Updated: 25-Jan-2018 17:07|