Strings in C++
Hello people, in this article we are going to study about a data structure Strings in C++ language. String is the only way by which we can set up a connection between english and programming language. Not only english, any other communicable language, for that matter.
A string is a collection of char variables in the form of arrays, this is a generic way of string implementation which is possible in C as well as in C++ language. This type of string is called C-style String. Also there exists another type of string implementation, which is an object of string class (The standard C++ ‘string’ library).
So, two implementations of strings are as follows :
C-Style String
Strings that are objects of string library.
C-Style String
C-strings are arrays of type “char” terminated with a null character, i.e., ‘\0’.
Defining a string :
char str[] = “C++”;
Alternate ways of defining a string :
char str[4] = “C++”;
char str[] = { ‘C’ , ’+’ , ’+’ , ‘\0’ };
char str[4] = { ‘C’ , ’+’ , ’+’ , ‘\0’ };
It is not necessary to use all the space allocated during the declaration, as we need to do in array :
char str[100] = “C++”;
Example of a program which reads a single word from the user :
To read the text containing blank space, “cin.get” function can be used. This function takes two arguments.
First argument is the
name of the string (address of first element of string) and second argument is
the maximum size of the array.
String Object
In C++, you can also create string objects for holding
strings.
Unlike using “char”
arrays, string object has no fixed length, and can be extended as per requirement.
An example declaration of string using string data type is
given below, here string(str) is
declared using string object. Here we ask user to enter the string.
Instead of using “cin>>”
or “cin.get()” function, you can
get the entered line of text using “getline()”.
“getline()” function takes the input stream as the first parameter which is “cin” and “str” as the location of line is to be stored.
We are coming with a series of posts regarding various data structures and their implementations. Do subscribe to our daily blog update by clicking here.
We want to acknowledge, Reema Thareja Ma'am, her book Data Structures Using C helped us alot during our research for this article, also this is the best one, you should go for.
If you still have any doubt on this topic then do come to us via email "sophomoretechs@gmail.com" or via instagram "@coding.winds".
No comments:
Post a Comment