Loading...
C++ Strings

C++ Strings

In this tutorial, you'll learn to handle strings in C. You'll learn to declare them, initialize them and use them for various input/output operations.


Strings

  • A string is a Variable that stores a sequence of letters or other characters.
  • Such as "Hello" or "March 3rd is my birthday!".
  • Just like the other data types, to create a string we first declare it, then we can store a value in it.

Types of strings

There are two types of strings commonly used in C++ programming language:

  • std::string (The Standard C++ Library string class)
  • C-strings (C-style Strings)

C-strings

  • In C programming, the collection of characters is stored in the form of arrays, this is also supported in C++ programming. Hence it's called C-strings.
  • A null terminated string, also called as C-string.
  • C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value of null character is 0).
  • Strings of these forms can be created and dealt with using <cstring> library.
  • Note : the null character may not be the last character in the C-string array.


How to define a C-string?

char str[] = "you";

In the above code, str is a string and it holds 4 characters.

Although, "you" has 3 character, the null character \0 is added to the end of the string automatically.


Alternative ways of defining a string

char str[4] = "you";

char str[] = {'y','o','u','\0'};
                                                          
char str[4] = {'y','o','u','\0'};

Like arrays, it is not necessary to use all the space allocated for the string. For example:

char myString[7] = "hello";
C++ C-style string
C-style string in C++ Programming

Example 1: Program to print a string

Let's write a very simple program, where we will declare and define an array of intergers in our main() function and pass one of the array element to a function, which will just print the value of the element.

// C++ program to display a string.
#include <iostream>
using namespace std;                                                  
int main(){
    char myStr[7] = "Hello"; // initialization

    cout <<myStr<<endl; // printing

    return 0;
}

Output

Hello

Example 2: C++ String to read a word entered by user

// C++ program to display a string entered by user.
#include <iostream>
using namespace std;
int main(){
    char myStr[50]; // initialization
    
    cout << "Enter a string: ";
    cin >> myStr;

    // Printing
    cout << "You entered: " << myStr << endl;
                                                                      
    cout << "\nEnter another string: ";
    cin >> myStr;

    // Printing
    cout << "You entered: " << myStr << endl;

    return 0;
}

Output

Enter a string: hello
You entered: hello
                                                                      
Enter another string: Hello World
You entered: Hello

Notice that, in the second expression only "Hello" is displayed instead of "Hello World".

This is because the extraction operator >> works as scanf() in C and considers a space " " has a terminating character.


Example 3: C++ String to read and display an entire line

// C++ program to read and display an entire line entered by user.

#include <iostream>
using namespace std;                                                                
int main(){
    char myStr[50];  // initialization
    cout << "Enter a string: ";
    cin.get(myStr, 50);

    // Print an entire line entered by user

    cout << "You entered: " << myStr << endl;
    return 0;
}

Output

Enter a string: C++ programming.
You entered: C++ programming.

Working of above program

  • To read the line containing blank space, cin.get function is 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.
  • In the above program, myStr is the name of the string and 50 is the maximum size of the array.

Disadvantages of this method

  • Size of the char array is fixed, which means more memory cannot be allocated at runtime.
  • In this method , we can only use the in-build functions created for array which don't help much in string manipulation.

String Object

  • A C++ string is an object that is a part of the C++ standard library.
  • String is defined by the class "std::string" is a representation of the stream of characters into an object. In other words, String class is a collection of string objects.
  • It is an instance of a "class" data type, used for convenient manipulation of sequences of characters.
  • To use the string class in your program, the <string> header file must be included.
  • The standard library string class can be accessed through the std namespace.

How to define a C String Object?

To use String object in our program we need to include header file as follows.

#include <string>

we declare Variables of type std::string as follows.

std::string str;

Here, str is a string variable just like we have int variables, float variables or variables of other dara types.

We assign value to a string variable just as we assign value to a variable of any other data type as follows.

str = "hello";

A string variable is just like any other variable.


Example 4: C++ Program to diaplay a string

// C++ program to read and display an entire line entered by user.

#include <iostream>
using namespace std;                                                                
int main(){
    string myStr; // Declaring a string object
    cout << "Enter a string: ";
    getline(cin, myStr);

    cout << "Displaying entered string: " << myStr << endl;
    return 0;
}

Output

Enter a string: C++ programming.
Displaying entered string: C++ Programming.

In this program, a string myStr is declared. Then the string is asked from the user.

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 myStr as the location of the line to be stored.


Example 5: C++ Passing String to a Function

#include <iostream>
using namespace std;
void show(char *);
void show(string);

int main(){
    string myStr1;
    char myStr[100];
                                                                      
    cout << "Enter a string: ";
    getline(cin, myStr1);

    cout << "Enter another string: ";
    cin.get(myStr, 100, '\n');

    show(myStr1);
    show(myStr);

    return 0;
}                                                                  
void show(char a[]){
    cout << "Display Entered char array is: " << a << endl;
}                                                                  
void show(string a){
    cout << "Display Entered string is: " << a << endl;
}

Output

Enter a string:  C++ Programming.
Enter another string:  are you sure?
Display Entered string is: C++ Programming.
Display Entered char array is: are you sure?

Working of above program

  • In the above program, two strings are asked to enter. These are stored in myStr and myStr1 respectively, where myStr is a char array and myStr1 is a string object.
  • Then, we have two functions show() that outputs the string onto the string.
  • The only difference between the two functions is the parameter. The first show() function takes char array as a parameter, while the second takes string as a parameter.
  • This process is known as function overloading. Learn more about Function Overloading.

Operations on Strings

Operations on string are divided into 4 category:

  • Input Functions
  • Capacity Functions
  • Iterator Functions
  • Manipulating Functions

Learn more about operations on string.


Next Tutorial

We hope that this tutorial helped you develop better understanding of the concept of String in C++.

Keep Learning : )

In the next tutorial, you'll learn about C++ Structure.

- Related Topics