C++ Strings

StringViews 2616

C++ provides three basic ways to create and use strings in our program:

  1. Using an array of char elements
  2. Using string class
  3. Using wchar_t for wide characters

Array of chars

String is a sequence of characters. char data type is used to represent one single character in C++. So if you want to use a string in your program then you can use an array of characters. The declaration and definition of the string using an array of chars is similar to declaration and definition of an array of any other data type:

//define an array of chars with 10 elements
char msg[10] = { 'M', 'E', 'S', 'S', 'A', 'G', 'E', '\0' };

Any string ends with a terminating null character ‘\0’. An array definition in such a way should include null character ‘\0’ as the last element. In above case the capacity of an array is 10 but we have used only 8 of it. The remaining two chars of an array will not be defined.

Another way to declare and define an array of characters of dynamic length as shown below:

char msg2[] = { 'M', 'E', 'S', 'S', 'A', 'G', 'E', '\0' };

In above case the amount of allocated memory will be exactly same as needed to store the sequence of characters.

The simplest way to initialize an array of characters is to use string literal in double quotes as shown below:

char msg3[] = "Message";

You can perform some basic operations on char arrays using functions from cstring library such as:

Copy one string to another

strcpy_s(destination, source)

Below is the demo of using strcpy_s

char msg[10] = { 'M', 'E', 'S', 'S', 'A', 'G', 'E', '\0' };
char dest[20];
strcpy_s(dest, msg);
cout << "String copied from msg = " << dest << endl;

The output of above example is shown below

String copied from msg = MESSAGE

Concatenate one string to another one

strcat_s(string1, string2)

string2 will be appended to the end of the string1

//declare 2 messages
char string1[20] = "Good";
char string2[] = " Morning";
//concatenate strings
strcat_s(string1, string2);
cout << string1 << endl;

The output os above program will be:

Good Morning

Note: You must have enough free space in string1 to concatenate it with string2.

Get length of the string

cout << "Length of the string 2 is " << strlen(string2) << endl;

Output of above code will be

Length of the string 2 is 8

String: “Morning” is stored in 7 characters and the 8th character is null character – ‘\0’

Compare two strings

strcmp(string1, string2)

This function will return 0, if the strings are equal; negative value, if string1 is less than string2 and positive value if string1 is greater than string2.

//declare two strings
char str1[100];
char str2[100];
//get user input of strings:
cout << "Please enter the first string\n";
cin >> str1;
cout << "Please enter the second string\n";
cin >> str2;
//compare strings
int result = strcmp(str1, str2);
if (result == 0)
	//strings are equals
	cout << str1 << " is equal to " << str2 << endl;
	if (result > 0)//str1 is greater
		cout << str1 << " is greater than " << str2 << endl;
	else//str2 is greater
		cout << str1 << " is less than " << str2 << endl;

Below is the output of above program

Please enter the first string
Please enter the second string
abc is less than abd

strcmp compares strings in lexicographical (alphabetical) order. “less than” for strings means that “cat” is less than “dog” because “cat” comes alphabetically before “dog”.

String Class

Another way to represent strings by using a class that is provided by standard C++ Library. This class is named string and it has much more functionality than char arrays in C++. Using “string” class in your programs offers you more capabilities. To use strings in your program you have to add the following include statement:

#include <string>

After including this header file you will be able to use string objects in your program. Here are example of declaring and defining a string:

string s1 = "Have a";
string s2 = " nice day";

The work with string class is very easy.

Concatenate Strings

To concatenate to strings use the plus sign:

string s3 = s1 + s2;
cout << s3 << endl;

Below is the output of above code

Have a nice day

Length of a String

To get the length of a string, for example, “s3”, you can use the following function


Example of getting string length

cout << "Length of s3 is " << s3.length() << endl;

Below is the output of above code

Length of s3 is 15

Copy one string into another

To copy one string to another just use the assignment operator

string s4 = s2;
cout << s4 << endl;

Below is the output os above code

nice day

Convert string into constant character array

Sometimes it’s useful to convert a string object to the constant char array. You can do this by using c_str() function as shown below

const char* cstr = s3.c_str();

Check if String is empty or not

You can use the empty() function of string to determine whether the string is empty or not. If a string is empty, function empty() will return true otherwise false

Below is the code shown how to use empty()

if (s4.empty())
	cout << "s4 is empty" << endl;
	cout << s4 << endl;

String class provides a lot of capabilities for the programmer to manipulate strings, but we are discussing now only the basic things. We will cover more about string class in next topics.

Wide characher wchar_t

Wide character wchar_t is a data type that has a size greater than simple character data type. This datatype occupies “2 or 4” bytes. This type provides capability to use extended character sets to represent strings. Mostly the wchar_t datatype is used when international languages like Chinese, Japanese are used. C++ provides built in data type to represent wchar_t wide characters.

Declaration of wide character variable can be done in the following way:

wchar_t wideString;

To use an array of wide characters you have to declare an array of wchar_t as shown below:

wchar_t wideString[100];

To work with wchar_t type you have to include the wchar library in your program as shown below:

#include <wchar.h>

Wchar library offers different functions and constants to work with wide characters. There are several constants in wchar library:

  • NULL – Represents null pointer constant.
  • WCHAR_MAX – Represents the maximum value of whcar_t
  • WCHAR_MIN – Represents the minimum value of wchar_t.
  • WEOF – Constant used to indicate the end of file.

To assign a value to a wide character string you have to use swprintffunction:

int swprintf (wchar_t*  destinationString, size_t length, const wchar_t* formatString, ...);

Here the parameters are:

  • Destination String – Wide characters that will hold the formatted data. It can be an array of wchar_t or a single wide character.
  • Length – The number of characters got written. You should remember to increment the length of string by one for null character at the end of the string.
  • Format String – String used to write the data according to the format.
  • … – The parameters to be used with the format string.

On success the return value of this function is the number of characters got written.

Below is an example

swprintf(wideString, 6, L"HELLO");

In above case, the format string is a simple string and the “L” character before “HELLO” is used to convert string to a const wchar_t*

The next example shows how to use format string with format specifiers:

swprintf(myMessage, 13, L"My age is %d ", 20);

In above case myMessage variable will contains “My age  is 20”.

The list of some format specifiers is represented in the following table:

 d, iDecimal or integer. The argument is an integer value
 UUnsigned integer
 OOctal integer
 x,XHexadecimal integer
 FFloating point value
 EScientific floating point
 nPointer to int

To print the wide characters we should use wpritnf function:

int wprintf (const wchar_t* formatString, ...);

wprintf writes wide characters to the standard output with the specified format. For example, we can print the value of two wide character strings used in the above code as below


To write wide characters to the standard output you can use wcout object in the same way as you used cout to output data.

wcout << "Use of wcout " << wideString << endl;

To read a wide character from console you have to use wcin instead of cin

wchar_t name[50];
cout << "Enter your name" << endl;
wcin >> name;
cout << endl << "Your name is ";
wprintf(L"%s", name);


Translate »