Strings in C/C++ Concepts you need to Learn to Stand Alone

Are you aware of strings in C/C++?

Strings in C and C++ are nothing but an array of characters terminated by the null character ‘\0’. Let us acknowledge the significance of strings in C/C++ by considering a simple problem.

Suppose you want to store the details of several employees such as their names, address, and qualification. It is pretty obvious that we can’t use any other data type except strings, as these records contain more than one letter. We can perform strings manipulation in the C/C++. This gives birth to even more applications of strings and makes it all the more significant.

1. What are Strings in C and C++?

In layman language, strings are nothing but a set of characters treated as a single entity.

In programming terminology, a string is:

  1. A one-dimensional array of characters.
  2. Enclosed within double quotes.
  3. Terminated with a null character, i.e. ‘\0’ automatically by the C/C++ compiler.

String in C and C++

 

2. Declare Strings

Strings are declared in the same way as arrays in C/C++, but restricted to the char data type. It is important to declare the string before using it. The C/C++ compiler reserves a specific block of memory for the sequence of characters. At the end of the string, we append the null character.

C++ has an upper hand over C as a string in C++ can be implemented in 2 ways:

  1. As an array of characters
  2. Using the predefined data type – “string”.

Its basic syntax is in C/C++

char string_name [ 30 ]; // Here 30 blocks of memory is reserved for the string

The basic syntax exclusively available in C++ is:

/* A string data type occupies 32 bytes in the computer memory according to a 64-bit compiler */

string string_name;

In order to perform string manipulations, it is mandatory to use the header file supported by the C/C++ standard library, namely:

#include<string.h>

Create your own Header Files in C  within Seconds

3. Initialize Strings

You can initialize Strings in C in different ways:

Let us consider some examples to demonstrate the various methods to declare a string:

char name[ ] = “DataFlair”;
char name[ ] = {'D' , 'a' , 't' , 'a' , 'F' , 'l' , 'a' , 'i' , 'r' , ‘\0’ };
char name [ 30 ] = ”DataFlair”;
char name [ 30 ] = {'D' , 'a' , 't' , 'a' , 'F' , 'l' , 'a' , 'i' , 'r' , ‘\0’ };

You can initialize a string in C++ in different ways:

Let us consider some examples to demonstrate the various methods to declare a string:

char name[ ] = “DataFlair”;
char name[ ] = {'D' , 'a' , 't' , 'a' , 'F' , 'l' , 'a' , 'i' , 'r' , ‘\0’ };
char name [ 30 ] = ”DataFlair”;
char name [ 30 ] = {'D' , 'a' , 't' , 'a' , 'F' , 'l' , 'a' , 'i' , 'r' , ‘\0’ };
string name = “DataFlair”;

4. Memory Occupied by Strings in C/C++

We have already discussed that a character occupies 1 byte of memory in Data Types in C/C++Similarly, a string, if initialized first, would occupy the memory:

(Number of characters in the string) x 1 byte + 1 byte

Key takeaway: 1 byte is added while calculating the size of the string. It is because the C/C++ compiler automatically appends the null character, i.e. ‘\0’. This null character consumes 1 byte of memory in the system.

Let us get back to the above example:

char name[ ] = “DataFlair”;

There data given below should be made in the form of a table

name[0] name[1] name[2] name[3] name[4] name[5] name[6] name[7] name[8] name[9]

DataFlair\0

Memory Occupied by Strings

 

Example of sizeof() operator in C

Here is a program in C that illustrates the amount of memory allocated to strings with the help of sizeof() operator.

#include<stdio.h>
int main()
{

printf("Welcome to DataFlair tutorials!\n\n");

char name1[] = "DataFlair";
char name2[] = {'D' , 'a' , 't' , 'a' , 'F' , 'l' , 'a' , 'i' , 'r' , '\0' };
char name3[30] = "DataFlair"; // 30 bytes is already allocated
char name4[30] = {'D' , 'a' , 't' , 'a' , 'F' , 'l' , 'a' , 'i' , 'r' , '\0' }; //30 bytes is already allocated
char name5[] = "Data Flair"; //a blank character occupies 1 byte of memory

printf("Size of %s is: %ld \n",name1,sizeof(name1));
printf("Size of %s is: %ld \n",name2,sizeof(name2));
printf("Size of %s is: %ld \n",name3,sizeof(name3));
printf("Size of %s is: %ld \n",name4,sizeof(name4));
printf("Size of %s is: %ld \n",name5,sizeof(name5));
return 0;
}

It’s time to explore Standard Library Function in C

Code on Screen-

Example of memory allocated to strings

Output-

memory allocated to strings

Example of sizeof() operator in C++

Here is a program in C++ that illustrates the amount of memory allocated to strings with the help of sizeof() operator:

#include <iostream>
using namespace std;

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

char name1[] = "DataFlair";
char name2[] = {'D' , 'a' , 't' , 'a' , 'F' , 'l' , 'a' , 'i' , 'r' , '\0' };
char name3[30] = "DataFlair"; // 30 bytes is already allocated
char name4[30] = {'D' , 'a' , 't' , 'a' , 'F' , 'l' , 'a' , 'i' , 'r' , '\0' }; //30 bytes is already allocated
char name5[] = "Data Flair"; //a blank character occupies 1 byte of memory
string name6 = "DataFlair";

cout<<"Size of " << name1 << " is: "<< sizeof(name1) <<endl;
cout<<"Size of " << name2 << " is: "<< sizeof(name2) <<endl;
cout<<"Size of " << name3 << " is: "<< sizeof(name3) <<endl;
cout<<"Size of " << name4 << " is: "<< sizeof(name4) <<endl;
cout<<"Size of " << name5 << " is: "<< sizeof(name5) <<endl;
cout<<"Size of " << name6 << " is: "<< sizeof(name6) <<endl;

return 0;
}

Code-

Example of sizeof() operator in C++

Output-

Output of sizeof() operator in C++

5. Read and Display String in C and C++

Example to read and display strings in C

Here is a code in C that illustrates how to take a string as an input from the user and display it:

#include <stdio.h>
int main()
{

printf("Welcome to DataFlair tutorials!\n\n");

char name[30];
printf("Enter the string: ");
scanf("%s", name);
printf("The string is %s\n", name);
return 0; 
}

Code on Screen-

Read and Display String in C

Output-

Read and Display string in C

Example to read and display strings in C++

Here is a code in C++ that illustrates how to take a string as an input from the user and display it:

#include <iostream>
using namespace std;

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl;

string name;
cout<<"Enter the string: ";
cin>>name;
cout<<"The string is "<< name <<endl;
return 0; 
}

Code-

Example to read and display strings in C++

Output-

Output of read and display strings in C++

6. Read and Display a Line using Strings in C/C++

In the C language, there are 2 important inbuilt functions in C/C++ that help you to read and print a line.

  1. gets(): It is similar to scanf() which helps you take a line as input.
  2. puts(): It is similar to printf() which helps you display a line as output.

But there is a problem associated with gets() which makes it dangerous to use because of Buffer Overflow as gets() as it is not capable of performing the array bound test. Hence, it is deprecated. To overcome this problem, fgets() is used instead of gets().

Example to read and display line using strings in C

Here is a code in C that illustrates how to read and display a line using strings with the help of fgets() and puts() functions:

#define STRING_SIZE 30
#include <stdio.h>
int main()
{

printf("Welcome to DataFlair tutorials!\n\n");

char line[STRING_SIZE];
printf("Enter a sentence ");
fgets(line, STRING_SIZE, stdin); // To read the string
printf("The sentence is: ");
puts(line); // To display the string
return 0;
}

Code on Screen-

Read and display lines in Strings in C

Output-

Read and Display a Line using Strings in C

In C++, there are 5 important inbuilt functions that help you perform input/output operations:

  • getchar(): This function returns a single character from the standard input device.

Syntax – character_type_variable = getchar();

For instance,

char letter;
letter = getchar();

Take a Break and Learn Variables in C/C++

  • putchar(): This function transmits a single character to the standard output device.

Syntax – putchar (character_type_variable);

For instance,

char letter;
putchar (letter);

  • gets(): This function is used to take string input. It accepts only one argument.

Syntax – gets (character_type_variable)

For instance,

char letter;
gets ( letter );

  • puts(): This function is used to display the string output. It also accepts only one argument.

Syntax – puts (character_type_variable)

For instance,

char letter;
puts ( letter );

  • getline(): This function is used to read a line to the standard input device.

Syntax – getline (cin, string_type_variable)

For instance,

string letter;
getline ( cin, letter );

Key takeaway: In C++, there is no such thing as “putline()” function.

Example of C++ string input/output functions

Here is a code in C++ that illustrates the use of some basic string input/output functions:

#include <iostream>
#include<string.h>
#include<sstream>
using namespace std;

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

char letter;
char word[30];
string line;

cout<<"Enter a character: ";
letter = getchar();

cout<<"Enter a string: ";
cin.ignore();
cin>>word;

cout<<"Enter a sentence: ";
cin.ignore();
getline(cin, line);

cout<<"\nThe character is: ";
putchar(letter);
cout<<endl;

cout<<"The string is: "<< word <<endl;

cout<<"The sentence is: "<< line <<endl;

return 0;
}

Code-

Example of C++ string input/output functions

Output-

Output of C++ string input-output functions

Master the Concept of Polymorphism in C++ in a few minutes

7. Various Functions in Strings

The C++ language offers various functions associated with strings.

Here is a table that succinctly summarizes some of the basic functions available for string manipulations:

FunctionMeaningElucidation
strlen(s)String LengthWe use it to find the length of the string.
strcpy(s1,s2)String Copy
We use to copy the value of the second string argument to the first string argument.
strcat(s1,s2)String Concatenation
We use to join the second string argument to the end of the first string argument.
strcmp(s1,s2)String Compare
We use it to compare both the string arguments.
It will return:
0, if s1 and s2 are equal; Less than 0 if s1<s2; Greater than 0 if s1>s2
strlwrString Lower
We use it to convert all the characters in the string to lowercase characters.
struprString Upper
We use it to convert all the characters in the string to uppercase characters.
strncatString Concatenation of n characters
We use it to join the first n characters to the end of the first string.
strncpyString Copy of n characters
We use it to copy the first n characters of one string to the other.
strncmpString Compare of n characters
We use it to compare the first n characters of both the strings in C.
strcmpi / stricmpString Compare without being case sensitive
We use it to compare both the strings without being case sensitive.
strnicmpString Compare of n characters without being case sensitive
We use it to compare the first n characters of the string without being case sensitive.
strdupString DuplicateWe use it in the duplication of a string.
strchrString First Character Occurrence
We use it to find the first occurrence of a specific character in the string.
strrchrString Last Character Occurrence
We use it to find the last occurrence of a specific character in the string.
strstrString Occurrence in String
We use it to find the first occurrence of a string in another string.
strsetString set
We use it to set all the characters of a string to a specific character.
strnsetString set of n characters
We use it to set the first n characters of a string to a specific character.

Learn Virtual Function in C++ with Real-time Example

Example in C

Here is a code in C that illustrates the use of the 4 basic functions:

  1. strlen()
  2. strcpy()
  3. strcmp()
  4. strcat()
#include <stdio.h>
#include <string.h>
int main ()
{
printf("Welcome to DataFlair tutorials!\n\n");

char s1[30] = "Data";
char s2[30] = "Flair";
char s3[30];
int length;

length = strlen(s1); // length of s1
printf("The length of s1 = %s is: %d\n", s1, length);

strcpy(s3, s1); // s1 is copied in s3
printf("The copied value of s3 is: %s\n", s3 );

if (strcmp(s1, s3) == 0) // both are equal as s1 is copied in s3
{
printf("s1 and s3 are equal\n");
}
else
{
printf("s1 and s3 are not equal\n");
}

strcat( s1, s2); // appends s2 at the end of s1
printf("The concatenation of s1 = %s and s2 = %s is: %s\n", s1, s2, s1);
return 0;
}

Code on Screen-

Functions in C Strings

Output-

Functions in C Strings

Example in C++

Here is a code in C++ that illustrates the use of the 4 basic functions:

  • strlen()
  • strcpy()
  • strcmp()
  • strcat()
#include <iostream>
#include <string.h>
using namespace std;

int main ()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

char s1[30] = "Data";
char s2[30] = "Flair";
char s3[30];
int  length;

length = strlen(s1); // length of s1
cout<<"The length of s1 = "<< s1 << " is: " << length <<endl;;
 
strcpy(s3, s1); // s1 is copied in s3
cout<<"The copied value of s3 is: "<< s3 <<endl;

if (strcmp(s1, s3) == 0) // both are equal as s1 is copied in s3
{
cout<<"s1 and s3 are equal"<<endl;
}
else
{
cout<<"s1 and s3 are not equal"<<endl;
}

strcat( s1, s2); // appends s2 at the end of s1
cout<<"The concatenation of s1 and s2 is: "<< s1 <<endl;
return 0;
}

Code-

Example of Functions in Strings in C++

Output-

Output of Functions in Strings in C++

8. Passing String to a Function

Functions are nothing but a fragment of code written to serve a specific purpose. We use it instead of piling all the logical statements onto the main function. It increases the code readability and enhances the reusability feature in the C programming language.

Various arguments or parameters can be passed to a function according to the programmer’s requirement.

Example of Passing String to a Function in C

Here is a code in C that illustrates how a string is passed to a function:

#include <stdio.h>
void display(char string[]); // Function declaration with string as parameter

int main()
{

printf("Welcome to DataFlair tutorials!\n\n");

char string[30];
printf("Enter the string: ");
fgets(string, 30, stdin);
display(string); // Passing the string to the function display
return 0;
}
void display(char string[])
{
printf("The string is: ");
puts(string);
}

Code on Screen-

Passing Functions to the strings in C

Output-

Output of Passing Functions to the strings in C

Example of Passing String to a Function in C++

Here is a code in C++ that illustrates how a string is passed to a function:

#include <iostream>
using namespace std;

void display(string line); // Function declaration with string as parameter

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

string line;
cout<<"Enter the string: ";
getline(cin, line); 
display(line); // Passing the string to the function display 
return 0;
}
void display(string line)
{
cout<<"The string is: "<<line<<endl;
}

Code-

Example of Passing String to a Function in C++

Output-

Output of Passing String to a Function in C++

9. Summary

In this tutorial, we discussed the meaning of Strings in the C and C++ Programming Languages. We acknowledged its significance by considering a simple problem. By understanding that strings are nothing but an array of characters, we inferred how to declare and initialize them. Further, we carried on our discussion by developing an understanding of how memory is allocated to strings. Then, we saw how to read and display a word and a sentence using strings. We concluded our discussion by stating the various string functions followed by illustrative programs.

Don’t forget to check – Multi-dimensional Arrays in C

If you have any queries regarding Strings in C, kindly let us know in the comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.