Site icon DataFlair

Strings in C – C++ [with Examples & Quizzes]

String in C and C++

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 C/C++. This gives birth to even more applications of strings and makes it all the more significant.

Don’t forget to attempt the quiz on Strings in C and C++ at the end.

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.

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++

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

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]

D a t a F l a i r \0

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;
}

Code on Screen

Output

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-

Output-

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-

Output-

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

Output

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

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

Output

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

Syntax – character_type_variable = getchar();

For instance,

char letter;
letter = getchar();

Syntax – putchar (character_type_variable);

For instance,

char letter;
putchar (letter);

Syntax – gets (character_type_variable)

For instance,

char letter;
gets ( letter );

Syntax – puts (character_type_variable)

For instance,

char letter;
puts ( letter );

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-

Output-

7. Various Functions in Strings

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

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

Function Meaning Elucidation
strlen(s) String Length We 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
strlwr String Lower
We use it to convert all the characters in the string to lowercase characters.
strupr String Upper
We use it to convert all the characters in the string to uppercase characters.
strncat String Concatenation of n characters
We use it to join the first n characters to the end of the first string.
strncpy String Copy of n characters
We use it to copy the first n characters of one string to the other.
strncmp String Compare of n characters
We use it to compare the first n characters of both the strings in C.
strcmpi / stricmp String Compare without being case sensitive
We use it to compare both the strings without being case sensitive.
strnicmp String Compare of n characters without being case sensitive
We use it to compare the first n characters of the string without being case sensitive.
strdup String Duplicate We use it in the duplication of a string.
strchr String First Character Occurrence
We use it to find the first occurrence of a specific character in the string.
strrchr String Last Character Occurrence
We use it to find the last occurrence of a specific character in the string.
strstr String Occurrence in String
We use it to find the first occurrence of a string in another string.
strset String set
We use it to set all the characters of a string to a specific character.
strnset String set of n characters
We use it to set the first n characters of a string to a specific character.
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

Output-

Example in C++

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

#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-

Output-

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-

Output-

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-

Output-

Quiz on Strings in C – C++

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    #include
    #include
    using namespace std;

    int main()
    {
    string s=”Game”;
    s.push_back(‘s’);
    cout<<s;
    return 0;
    }

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    #include
    #include
    using namespace std;

    int main()
    {
    string s=”Run”;
    s.push_back(‘n’);
    s.pop_back();
    cout<<s;
    return 0;
    }

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    #include
    #include
    using namespace std;

    int main()
    {
    string s=”This is India”;
    s.resize(4);
    cout<<s;
    return 0;
    }

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    #include
    #include
    using namespace std;

    int main()
    {
    string str=”Delhi is the capital of India”;
    str.resize(10);
    cout<<str.capacity();
    return 0;
    }

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    #include
    #include
    using namespace std;

    int main()
    {
    string str=”Delhi is the capital of India”;
    str.resize(10);
    str.shrink_to_fit();
    cout<<str.capacity();
    return 0;
    }

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

    #include
    #include
    using namespace std;

    int main()
    {
    string str=”Delhi is the capital of India”;
    char c[12];
    str.copy(c,5,0);
    cout<<c;
    return 0;
    }

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    #include
    #include
    using namespace std;

    int main()
    {
    string str1=”ab”;
    string str2=”abb”;
    string str3=str1+str2;
    str1.swap(str3);
    cout<<str3;
    return 0;
    }

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    #include
    #include
    using namespace std;

    int main()
    {
    string str1=”Delhi”;
    string str2=”Mumbai”;
    string::iterator i;
    i=str1.begin();
    cout<<*i<<" ";
    i=str2.end();
    cout<<*i;

    return 0;
    }

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

    #include
    #include
    using namespace std;

    int main()
    {
    string str1=”Delhi”;
    string str2=”Goa”;
    string::reverse_iterator i;
    i=str2.rbegin();
    cout<<*i<<" ";
    i=str1.rend();
    cout<<*i;

    return 0;
    }

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    #include
    #include
    using namespace std;

    int main()
    {
    char str1[]=”Delhi”;
    char str2[]=”Goa”;
    cout<<strcat(str2,str1);

    return 0;
    }

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

    What class should be included to use function push_back()?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

    Memory allocation for character array is:

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

    What is not true among the following advantages of string over character array

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    rbegin() function returns:

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

    capacity() function returns:

    Correct
    Incorrect

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.

Exit mobile version