Skip to main content

C-style strings vs String Class.

Here, we are going to learn about, what are C-Style Strings and what is String class.

So, let's start by giving you the introduction.

C-Style String is nothing but, an array of characters, and from the term array we can surely assume that these are static in size i.e. the size of these C-Style strings cannot be increased or decreased.

String Class is a Built-in class that provide us much more functionality than C-Style String.

C-STYLE STRINGS

Before learning the String class, which is full-fledged feature of C++, we should rather start by taking a look at some important things about C-Style String.

C-Style Strings are actually array of characters that are terminated by a null character "\0". If you are confused with, why null character? The reason is that, It helps us to define, upto which index we have some useful data present in our character array, and after null character there may or may not be some garbage values of characters.

Let's first start by showing a program that how we could declare and initialize a C-Style String.

#include<iostream>
using namespace std;
int main(){
    
    char string1[30] = "YourCppTutor.Blogspot.com";     // #1

    char string2[30] = {'Y','o','u','r','C','p','p','T',
    'u','t','o','r','.','B','l','o','g','s','p','o',
    't','.','c','o','m'};                               // #2

    char *string3 = "YourCppTutor.Blogspot.com";        // #3

    char string4[30]{ "YourCppTutor.Blogspot.com" };    // #4

    cout << string1 << endl << string2 << endl << string3 << endl << string4 << endl;

    return 0;
}

As you can see there are three methods that I have shown here, but obviously you can even create a C-Style string dynamically and that is an exercise for you. But first, let me briefly explain what are these declaration and initialization doing.

  • #1 - Here we simply create a character array and initialize a value to it, Assigning like this is the easiest method of all.
  • #2 - Here we simply created character array and initialized it like we initialize any other ordinary array, but I won't prefer this method, it's tiring, just like I am tired of writing, such a small text, with many extra commas(,).
  • #3 - In this line I want to highlight something, You just have to remember this and make a sticky note on your mind that when ever you declare an array the identifier(name of the array) is actually not just an obvious thing, but actually it is a pointer, which points to the first element of the array, Why? Let's reason it in a logical way, think of the same #3 example, what we are doing here is declaring a character pointer, Now if you don't know this till now, then remember it, that every pointer in C++(e.g. char*, int*, void* etc) have equal size which is in turn equal to the size of the integer in our C++ compiler. and in my case it is 4 bytes, but, we are here storing a string of size 25 bytes(if I didn't counted wrong), and this is not possible to store 25 bytes in 4 bytes so, we rather store the address of the first element of the array to our identifier rather than the whole string, this is also impacted by the fact that array occupies contiguous memory locations, and if we got address of first element, we can get up-to last element easily. One more thing to notice in this line is that, if you run it in your personal IDE, it can give you some warning about converting a string constant into char *, the simple reason you can assume is that, it is happening due to pointer, but I will clear your doubt, when we learn about const keyword.
  • #4 - It is nothing but a different style of parsing parameters to some object, you will learn about this, when we start covering OOP(Object Oriented Programming).
NOTE - The size of the character array should always be 1 greater than the number characters you want to store, because, we have to ensure that there is enough space for the null character ('\0'), I will not be showing much about this, because it is something you could find with a single web search.

As of now, we have seen how to declare and initialize the C-Style String, So, Now let's read functions that can be used on C-Style String. 

I found this insanely good article, on C-Style Strings functions.
Welcome, back If you read the article that I gave the link above, you are good to continue with the rest of the article.

Now, let's see, How can you take input in your Character-Array (C-Style String) in c++.
Actually there are number of ways for doing so, I will not be taking about scanf here.

#include<iostream> 		// cin and cout present in this header
#include<stdio.h>		// stdin and stdout present in this header
using namespace std;
int main(){

	char array1[10];
	char array2[10];
	char array3[10];
	char array4[10];

	gets(array1);					//	--		#1
							//	|
	fgets(array2, sizeof(array2), stdin);		//	|		#2
							//	|--  input
	cin >> array3;					//	|		#3
							//  	|
	cin.getline(array4, sizeof(array4));		//      -- 

	/*
	Try to learn about scanf and printf
	by yourself.
	*/
	puts(array1);			//	--		#1
					//	|
	fputs(array2, stdout);		//	|-- output	#2
					//	|
	cout << array3 << endl;	        //	--		#3

	return 0;
}

Above I have shown three different ways, of getting input in the C-Style String and getting output from the C-Style String. Now, let's discuss them -

  1. Here I used gets for input and puts for output.
    • gets() - I will not prefer you to use gets(), for taking input in a C-Style String, because, it do not behave desirable, when there is overflow of character in your input array, For example. Try to run the above program in local machine and input a string which has a length greater than 10, You will see that program will not produce any kind of exception in its behaviour, even if there is overflow of character, which is a bad practice in the field of computer programs.
    • puts() - It simply prints the C-Style String, passed as a parameter.
  2. Here I used fgets() and fputs() for input an output
    • fgets(Char arary, Number_of_char, file stream) - If you want your program to work exactly according to you, you should always use this one for taking input in a C-Style String, As it also enables us to provide a parameter, about, how many characters will be entered in that particular string. Remember, here I used stdin, because, my stream of input character is coming from my system keyboard, you can use it for taking input from files also, which we shall see in file handling in later sections.
    • fgets(char array, file stream) - Simply print.
  3. It's just basic input stream and output stream.
  4. I have not numbered the line cin.getline(array4, sizeof(array4)), Because, whenever you do this, you must first have to be aware of, about, is there any input stream before this line, and if not, you are good to go, and if there is some input stream before this one, you have flush your input buffer before using this one statement or you have to take care of extra '\n' character in your input stream. I will not be showing about clearing input and output buffers here, but to run this particular program correctly, what you could do is declare a single character and take input in that character before writing this "cin.getline()" statement. If you successfully fixed this, please share your code in comment box.

STRING CLASS

I hope that you have properly understood about C-Style strings. So, let's further due, we shall start our discussion on string class.
Let me first tell you the biggest difference between C++ String Class and C-Style Strings.
C-Style String is an array of characters terminated with a null character, which makes its size static, while C++ String Class are the objects, which automatically manages the memory, which makes it much safer to use, as you don't have to worry about adding some number characters makes the string overflow or not. Due to which, it facilitates us to use very powerful function on strings like Concatenation and "+" operators.
String Class also help us to prevent the issue of array decay, Let' first take an example.

#include<iostream>
using namespace std;
void Print(char *string1){
    cout << "In function we have size : " << sizeof(string1) << endl;
}
int main(){
	
    char string1[100] = "YourCppTutor.Blogspot.com\0somethingblaablaa....";

    cout << "In main we have size : " << sizeof(string1) << endl;

    /*
    This is a perfect example of seeting how array decay occurs
    first let's see what happens, and after that, we will define 
    what array decay actually means.
    */
    
    Print(string1);

    return 0;
}

Output :-

In main we have size : 100
In function we have size : 4

Did, you see how we loss the original size of the array? This, is array decay in actual.

Array Decay - The loss of size or type of an array when passed as a parameter into a function is called array decay, remember that it only happens when we pass it as a pointer, or pass it by value. To avoid array decay we have to use the concept of pass by reference.
(Passing by reference, pointers, values will be covered in the next slide.)

String class is present inside C++ libraries since C++98. String class is very easy to use in many scenarios, where using C-Style String(Array of characters) seems somewhat tough and tiring.
Below program shows some basic syntaxes of declaring and initializing the String Class Objects :-
 

#include<iostream>
#include<string>
using namespace std;
int main(){

    string string1 = "YourCppTutor.Blogspot.com";       // #1

    string string2( "YourCppTutor.Blogspot.com" );      // #2

    string string3{ "YourCppTutor.Blogspot.com" };      // #3

    cout << string1 << endl << string2 << endl << string3 << endl;

    return 0;
}

Let's discuss the numbered lines one by one -

  • #1 - It is just an assignment operator. One thing you should remember is that when you declare an object of string class, it's default size will be zero and it is considered as an empty string, unlike the character array, where in each array position, we have some garbage value, if not assigned some useful value.
  • #2 - It is a copy constructor, as we are using " ( ) " brackets here.
  • #3 - Here we are sending the string "YouCppTutor.Blogspot.com" s a parameter, to be get stored in the data members of our class.
Okay, so we have covered some basic things about string class, Now, let's take a look at the main functionality of the string class, i.e. the member functions ( or simply function) you can use on string class objects.
I have created a separate HTML file for that functions reference, Here is the link.

At the end, let's try to answer the question, Which one to use?
For this, we need to see pros and cons of both of them, 
  • String class internally manages the memory, which makes it slow, so, C-Style string are good in terms of speed.
  • String Class contains a large set of manipulating functions, which makes it more user-accessible.
  • Managing memory internally is also an advantage of string class. Which makes it free to errors like memory overflow etc.
  • No, issue of array decay.
It depends on the user, which of them, he/she wants to use, or both of them.

Stay tuned for the upcoming content. For any query leave a comment below.

References.
  • Kent edu
  • Lippman, Stanley B. c++ primer 3rd edition(april 2, 1998).

Comments

Post a Comment

Popular posts from this blog

Introduction to Computer Science.

 Before directly jumping deeply in c++, let's first start by creating the roots of computer science. In this post we will answer the following question. What is Computer and How it works? What is Program and Operating system? Low Level vs High Level Language? Compiler v/s Interpreter? By Knowing All these basic concepts You will be able to understand the upcoming more complex concepts easily. Let's start answering the above questions. What is Computer and How it works? What is computer? If I answer briefly,  what is computer?  then it is just a calculator used for doing simple calculations. If I have to answer where is computer used?, then I could probably say everywhere. We are surrounded by computer, for example mobile, smartwatches, and personal computer (obviously).  The below image is the first mechanical computer that we used for calculation.                                   ...

Algorithms, Pseduocodes and FlowCharts.

Some Basic Knowledge. C++ is a general purpose programming language, created by Bjarne Stroustrup and was firstly released in  1985. It is an extension to C language, Reason for that is if you are familiar with C language than you must be familiar with the fact that there are no classes, templates etc. present in C language. Due to which when classes are added to C language it is named as "C with Classes", but C++ is considered as default name now.  Extra thing to remember - In "C++" the symbol "++" after C is post increment symbol and therefore, "C++" means that In C additional features are added. Now, let's define, what are algorithms? Algorithms are nothing but set of rules that must be followed to accomplish some task. (Now, What that mean?😕) let's take an example of swapping two numbers, i.e. if a = 10 and b = 20 after swapping a = 20 and b = 10. How will you write the procedure for this?  (There are many such algorithms). Accordin...