Close
Close

Strings in C++


We know that string is a collection of characters. Let's again have a look at string and learn more about it.

There are two different types of strings in C++.

  • C-style string
  • std::string (part of the standard library)

In this chapter, we will focus on C-style string.

C-style String


We can think of string as an array of characters, like "Sam" is a string and it is an array of characters 'S', 'a', 'm' and '\0'.

element 'S' 'a' 'm' '\0'
index 0 1 2 3

Look at the character at the 3rd index. It represents null character. ASCII value of '\0' is 0 and that of normal 0 is 48. It represents the termination of a string. So, if we declare :-

char name[ ]= "Sam";

It is :-
['S','a','m','\0']

We always put string in " ".

We can also declare a string variable using characters as follows.

char name[ ]= { 'S', 'a', 'm', '\0'};

Let's see two examples to print a string, one without and the other with for loop.

#include <iostream>

using namespace std;

int main(){
	char str[ ] = "Hello";
	cout << str << endl;
	return 0;
}
Output
Hello

In the above example, we printed the whole string at once. Now, let's see the same example of printing individual characters of the string using for loop.

#include <iostream>

using namespace std;

int main(){
	char str[ ] = "Hello";
  	int i;
  	for( i=0; i<6; i++)
  	{
    	cout << str[i];
  	}
	return 0;
}
Output
Hello

In the first example, we printed the whole string at once. Whereas in the second example, we printed a character each time.

Taking string input


Now let's see how to input string from the user with an example.

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

	char name[20];       //declaring string 'name'

	cin >> name; //taking string input
	cout << name << endl; //printing string
	return 0;
}
Output
Peter
Peter

char name[20]; - By writing this statement, we declared an array of characters named 'name' and gave it an array size of 20 because we don't know the exact length of the string. Thus, it occupied a space in the memory having a size that is required by 20 characters. So, our array 'name' cannot store more than 20 characters.
cin >> name; - This is used to simply input a string from the user as we do for other datatypes and there is nothing new in this.

The above code takes only one word from user to a string variable. It terminates with any white space. Try to write something after space and it will take only the first word.

For example, if in the above example, we input Sam Brad as the name, then the output will only be Sam because the code considers only one word and terminates after the first word (after a whitespace).

Taking multi-word string input


We can take input of a string that consists of more than one word by using cin.getline. Let's see an example:

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

	char name[20];       //declaring string 'name'

	cin.getline(name, sizeof(name)); //taking string input
	cout << name << endl; //printing string
	return 0;
}
Output
Sam Bard
Sam Bard

cin.getline(name, sizeof(name)); - cin.getline takes two arguments, the string variable and the size of that variable. We have used sizeof operator to get the size of string variable 'name'.

Pointers and String


Strings can also be declared using pointers. Let's see an example.

#include <iostream>

using namespace std;

int main(){
	char name[ ]= "Sam";
  	char *p;
  	p = name;     /* for string, only this declaration will store its base address */
  	while( *p != '\0')
  	{
    	cout << *p;
    	p++;
  	}
	return 0;
}
Output
Sam

In the above example, since p stores the address of name[0], therefore the value of *p equals the value of name[0] i.e., 'S'. So in while loop, the first character gets printed and p++ increases the value of p by 1 so that now p+1 points to name[1]. This continues until the pointer reaches the end of the string i.e., before *p becomes equal to '\0'.

Passing Strings to Functions


This is the same as we do with other arrays. The only difference is that this is an array of characters. That's it !

Let's see an example.

#include <iostream>

using namespace std;

void display( char ch[] ){
	cout << ch;
}

int main(){
	char arr[30];
	cout << "Enter a word" << endl;
	cin >> arr;
	display(arr);
	return 0;
}
Output
Enter a word
cpp
cpp

Predefined string functions


We can perform different kinds of string functions like joining of 2 strings, comparing one string with another or finding the length of the string. Let's have a look at the list of such functions.

Function Use
strlen calculates the length of string
strcat Appends one string at the end of another
strncat Appends first n characters of a string at the end of another
strcpy Copies a string into another
strncpy Copies first n characters of one string into another
strcmp Compares two strings
strncmp Compares first n characters of two strings
strchr Finds first occurrence of a given character in a string
strrchr Finds last occurrence of a given character in a string
strstr Finds first occurrence of a given string in another string

These predefined functions are part of the cstring library. Therefore, we need to include this library in our code by writing

#include <cstring>

We will see some examples of strlen, strcpy, strcat and strcmp as these are the most commonly used.

strlen(s1) calculates the length of string s1.

White space is also calculated in the length of the string.

#include <iostream>
#include <cstring>

using namespace std;

int main(){
	char name[ ]= "Hello";
  	int len1, len2;
  	len1 = strlen(name);
  	len2 = strlen("Hello World");
  	cout << "Length of " << name << " = " << len1 << endl;
  	cout << "Length of " << "Hello World" << " = " << len2 << endl;
	return 0;
}
Output
Length of Hello = 5
Length of Hello World = 11
strlen doesn't count '\0' while calculating length of string.

strcpy(s1, s2) copies the second string s2 to the first string s1.

#include <iostream>
#include <cstring>

using namespace std;

int main(){
	char s2[ ]= "Hello";
  	char s1[10];
  	strcpy(s1, s2);
  	cout << "Source string " << s2 << endl;
  	cout << "Target string " << s1 << endl;
	return 0;
}
Output
Source string Hello
Target string Hello

strcat(s1, s2) concatenates(joins) the second string s2 to the first string s1.

#include <iostream>
#include <cstring>

using namespace std;

int main(){
	char s2[ ]= "World";
  	char s1[20]= "Hello";
  	strcat(s1, s2);
  	cout << "Source string " << s2 << endl;
  	cout << "Target string " << s1 << endl;
	return 0;
}
Output
Source string World
Target string HelloWorld

Note that in the above example, we gave array size to s1 because we are adding the characters of another string to it. The array size given should be such that it is greater than or equal to the size of the string array after concatenation.

strcmp(s1, s2) compares two strings and finds out whether they are same or different. It compares the two strings character by character till there is a mismatch. If the two strings are identical, it returns a 0. If not, then it returns the difference between the ASCII values of the first non-matching pairs of characters.

#include <iostream>
#include <cstring>

using namespace std;

int main(){
	char s1[ ]= "Hello";
  	char s2[ ]= "World";
  	int i, j;
  	i = strcmp(s1, "Hello");
  	j = strcmp(s1, s2);
  	cout << i << endl;
  	cout << j << endl;
	return 0;
}
Output
0
-15

2 D Array of Characters


Same as 2 D array of integers and other data types, we have 2 D array of characters also.

For example, we can write

char names[4][10] = {
                                        "Andrew",
                                        "Kary",
                                        "Brown",
                                        "Lawren"
                                    };

Since string is used extensively, C++ provides a built-in string data type which you will learn in the next chapter.

To learn from simple videos, you can always look at our C++ video course on CodesDope Pro. It has over 750 practice questions and over 200 solved examples.

Without practice, your knowledge is poison.
-Chanakya

Ask Yours
Post Yours
Doubt? Ask question