Categories
Computer Science / Information Technology Language: C++

Strings

Introduction

  • To use strings in C++, one must include the string library as follows: #include <string>
  • C++ string and its rich set of methods are in the standard namespace (std).
  • Similar to C strings, C++ strings are stored in contiguous memory locations.
  • However, unlike C strings which are fixed in size, the C++ strings have dynamic size. That is, C++ strings can grow or shrink as needed in runtime.
  • C++ strings work with input and output streams.
  • Some of the arithmetic and comparison operators are compatible with C++ strings. Some of them are as follows:
    • Addition (+) for concatenation
    • Assignment (=)
    • Lesser than (<)
    • Lesser than or equal to (<=)
    • Greater than (>)
    • Greater than or equal to (>=)
    • Shorthand addition and assignment (+=) for concatenation and assignment
    • Equals to (==) for string matching
    • Not equals to (!=) for string matching
  • C++ gives the flexibility to convert C++ strings to C strings and vice-versa easily.
  • C++ are safer as it provides bound checking, dynamic sizing and various other features.

Declaration and Initialization

As noted earlier, to use C++ strings, one must include the string library and use the standard namespace. The syntax of the declaration of a C++ string is as follows:

string str_var;

Unlike C strings, the C++ strings are initialised by default at the time of declaration to an empty string, if nothing is explicitly specified.

There are various ways in which a C++ string can be initialised. They are described as follows:

  1. Initialising with a string literal.
string str_var {"string_literal"};
  1. Initialising with another string
string str_var {s2};

This makes a deep copy of s2 in str_var

  1. Initialise with the substring of a string literal
string str_var {“string_literal”, 3};

This initialises the first 3 characters of the string literal to str_var. That is, it initialises "str" to str_var.

  1. Initialise with a substring of another string
string str_var {s2, start_index, num_of_char};

This initialises str_var to substring of s2 from start_index and the length of the substring will be num_of_char

  1. Initialise with a character
string str_var (3, 'A');

This initialises str_var to a string of length 3 characters and contains only 'A'. That is "AAA".

Operators used on strings

The assignment operator (=)

The assignment operator can be used to deep copy the contents of one string to another. This is illustrated in the following example:

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1 = "Hello World";
    string s2 = s1;
    s2[2] = 'z';
    cout << s1 << endl;
    cout << s2;
    return 0;
}

Output:

Hello World
Hezlo World

Conclusion:

The assignment operator deep copies the contents of one string to another. Hence the changes made to one string don’t reflect in the other string.

Addition operator (+) for concatenation

The addition operator can be used to concatenate one C++ string to another. This is illustrated in the following examples:

Example 1
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1 = "Hello";
    string s2 = " World";
    string s3 = s1 + s2;
    cout << s3;
    return 0;
}

Output: Hello World

Conclusion: The addition operator can be used to concatenate two strings.

Example 2
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1 = "Hello";
    string s2 = s1 + " World!";
    cout << s2;
    return 0;
}

Output: Hello World!

Conclusion: The addition operator can concatenate a string variable with a string literal too.

Example 3
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1 = "Hello";
    string s2 = s1 + " World!" + " C++ is fun.";
    cout << s2;
    return 0;
}

Output: Hello World! C++ is fun.

Conclusion:

  • The addition operator can concatenate a string variable with a string literal too.
  • The addition operator can be used to concatenate multiple strings.

It is important to note that we cannot concatenate 2 C strings using the addition operator. At least one of the operands to the addition operator should be strictly C++ string.

Example 4

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1 = "Hello" + " World!";
    cout << s1;
    return 0;
}

Output: ERROR

Conclusion: The addition operator can concatenate a string variable with a string literal too.

The subscript operator ([])

To access individual characters of strings, one can use the subscript operator. This is illustrated in the following examples:

Example 1
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1 = "str";
    cout << "Character at index #0: " << s1[0] << endl;
    cout << "Character at index #1: " << s1[1] << endl;
    cout << "Character at index #2: " << s1[2];
    return 0;
}

Output: Hello World!

Example 2
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1 = "str";
    s1[1] = 'i';
    cout << s1;
    return 0;
}

Output: sir

Conclusion: The subscript notation can be used to modify strings at specific indices.

The at() method can also be used for the exact purpose for which the subscript operator is used. The syntax is as follows:

str_var.at(index);

The only difference between using the subscript notation and at() method is that the at() method is safe and if the index given as a parameter exceeds the size of the string, then it throws an exception.

Comparison operators

The C++ strings support the following comparison operators:

  • Lesser than (<)
  • Lesser than or equal to (<=)
  • Greater than (>)
  • Greater than or equal to (>=)
  • Equals to (==) for string matching
  • Not equals to (!=) for string matching

When these operators are used on C++ strings, the strings are compared character-wise lexically and the corresponding boolean values are returned.

The comparison operators have certain limitations. They can compare only certain combinations of string objects and C strings. The compatible combinations are listed as follows:

  1. Two std::string objects.
  2. std::string object and C-style string literal (character constant).
  3. std::string object and C-style string variable (character array).

Using a range-based for loop to iterate through a string

The range-based for loop can be used to conveniently iterate through the string. The following examples illustrate the same:

Example 1
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1 = "str";
    for (char ch: s1)
        cout << ch << " ";
    return 0;
}

Output: s t r

Example 2
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1 = "str";
    for (int ch: s1)
        cout << ch << " ";
    return 0;
}

Output: 115 116 114

Conclusion: The values from the iterable placed in a range-based for loop are type cased to the type of the iterator variable. In this case, it is the integer which depicts the ASCII values of the corresponding characters.

C++ string methods

MethodDescriptionReturn typeParameters
sizeReturn length of stringsize_tNone
lengthReturn length of stringsize_tNone
max_sizeReturns the maximum length the string can reachsize_tNone
resizeResizes the string to a length of n characters. If c is specified, the new elements are initialized as copies of c, otherwise, they are value-initialized characters (null characters)void(size_t n, char c)
Where c is optional
emptyTest whether the string is emptybooleanNone
capacityReturns the size of the storage space currently allocated for the string, expressed in terms of bytes.size_tNone
clearErases the contents of the string, which becomes an empty string (with a length of 0 characters)voidNone
reserveRequests that the string capacity is at least enough to contain 'n' elements.voidn
shrink_to_fitRequests the string to reduce its capacity to fit its size.voidNone
atAccess character at the specified indexcharIndex value between 0 and length – 1 inclusive
frontReturns a reference to the first character of the string.Char ReferenceNone
backReturns a reference to the last character of the string.Char ReferenceNone
appendExtends the string by appending additional characters at the end of its current valueString referenceTypical: (string str)

There are many versions of append. Please refer to the official documentation for details.
assignAssigns a new value to the string, replacing its current contents, and modifying its size accordingly.String referenceTypical: (string str)

There are many versions of append. Please refer to the official documentation for details.
push_backAppends character c to the end of the string, increasing its length by one.voidchar
pop_backErases the last character of the string, effectively reducing its length by one.voidNone
insertInserts additional characters into the string right before the character indicated by posAn iterator that points to the first of the newly inserted elements.Typical: (size_t pos, string str)

There are many versions of append. Please refer to the official documentation for details.
eraseRemoves from the string either a single char at a position or a range of elements ([start_idx, length))An iterator referring to the character that now occupies the position of the first character erased, or string::end if no such character exists.If no parameters are present, the method erases all characters in the string. Possible parameters:

1. (size_t position, size_t len)

2. Iterator pointing character to be removed.

3. Iterator to the first character to be removed and the last character to be removed
swapExchanges the content of the container by the content of str, which is another string object. Lengths may differvoidString
replaceReplaces the portion of the stringReference to stringTypical: (start_pos, length, string)

There are many versions of append. Please refer to the official documentation for details.
c_strReturns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.Pointer to a character arrayNone
dataReturns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.Pointer to character arrayNone
get_allocatorReturns a copy of the allocator object associated with the string.Allocator typeNone
copyCopies a substring of the current value of the string object into the array pointed by s. This substring contains the len characters that start at position pos.size_tchar* s, size_t len, size_t pos = 0
findSearches the string for the first occurrence of the sequence specified by its arguments.size_tA string or pointer to a character array or a character and a starting position
rfindFind last occurrence of content in stringsize_tA string or pointer to a character array or a character and a starting position
find_first_ofSearches the string for the first character that matches any of the characters specified in its arguments.size_tA string or pointer to a character array or a character and a starting position
find_last_ofSearches the string for the last character that matches any of the characters specified in its arguments.size_tA string or pointer to a character array or a character and a starting position
find_first_not_ofSearches the string for the first character that does not match any of the characters specified in its arguments.size_tA string or pointer to a character array or a character and a starting position
find_last_not_ofSearches the string for the last character that does not match any of the characters specified in its arguments.size_tA string or pointer to a character array or a character and a starting position
substrReturns a newly constructed string object with its value initialized to a copy of a substring of this object.stringstart position and length
compareCompares the value of the string object (or a substring) to the sequence of characters specified by its arguments.intTypically takes a string.

There are many versions of append. Please refer to the official documentation for details.
String methods

Reading strings from the console

Using cin

To read the string using the input stream through cin, the following syntax should be used:

string str;
cin >> str;

The above statement accepts the input string up to the first white space character. Consider the following examples:

Example 1
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1;
    cin >> s1;
    cout << "Entered string: " << s1;
    return 0;
}

Input: Hello

Output: Entered string: Hello

Example 2
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1;
    cin >> s1;
    cout << "Entered string: " << s1;
    return 0;
}

Input: Hello World

Output: Entered string: Hello

Conclusion: cin reads only up to the first whitespace character found.

Using getline() function

To read the entire line till the new line character, one can use getline() function. The syntax is as follows:

getline(cin, str);

The getline() function also has an optional 3rd parameter called delimiter. The delimiter is a character that when found in the input, the function getline() stops reading the input there. This is by default set to newline character if not mentioned. Consider the following examples:

Example 1
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1;
    getline(cin, s1);
    cout << "Entered string: " << s1;
    return 0;
}

Input: Hello World

Output: Entered string: Hello World

Conclusion: getline() reads the entire line, that is, up to the first occurrence of the newline character.

Example 2
#include <iostream>
#include <string>
using namespace std;
int main() {
    string s1;
    getline(cin, s1, 'r');
    cout << "Entered string: " << s1;
    return 0;
}

Input: Hello World

Output: Entered string: Hello World

Conclusion: If the delimiter is passed to getline(), it reads up to the first occurrence of the mentioned delimiter or the newline character, whichever comes first.

Note to readers

This note has provided content sufficient to start working with C++ strings. The reader has to work by solving examples to get familiarised with the methods the string class provides to get familiarised and comfortable with the C++ strings.

Exercises

  1. Write a function that accepts a string and deletes the last character.
  2. Write a function that accepts a string and deletes all the trailing spaces at the end of the string.
  3. Write a function that accepts a string and deletes all the leading spaces.
  4. Write a function that returns the number of times the character is found in a string. The function has two parameters: the first parameter is a pointer to a string and the second parameter is the character to be found.
  5. Write a function that inserts a string into another string at a specified position. It should return the new string. The first parameter is the receiving string. The second parameter is the string to be inserted. And the third parameter is the index of the insertion position in the first string.
  6. Write a program that extracts part of the given string from the specified position. For example, if the string is “Working with strings is fun”, then if from position 4, four characters are to be extracted, then the program should print the string as “king”. If the number of characters to be extracted is 0, then the program should print the entire string from the specified position. Make use of functions. The function should take the string, start index and the end index as parameters and should return the substring.
  7. Write a program that converts a string like “123” to an integer 123.
  8. To uniquely identify a book a 10 digit ISBN (international standard book number) is used. The rightmost digit is a checksum digit. This digit is determined from the other 9 digits using the condition that d1 + 2d2 + 3d3 + … + 10d10 must be a multiple of 11 (where di denotes the ith digit from the right). The checksum digit d1 can be any value from 0 to 10: the ISBN convention is to use the value x to denote 10. Write a program that receives a 10 digit integer, computes the checksum, and reports whether the ISBN number is correct or not.
  9. A credit card number is usually a 16 digit number. A valid credit card number could satisfy a rule explained below with the help of a dummy credit card number- 4567 1234 5678 9129. Start with the rightmost – 1 digit and multiply every other digit by 2.
4567123456789129
812261014184
  • Then, perform the following operations:
    • Subtract 9 from any number larger than 10. Thus we get:
      • 8 3 2 6 1 5 9 4
    • Add them all up to get 38.
    • Add all the other digits to get 42.
    • The sum of 38 and 42 is 80. Since 80 is divisible by 10, the credit card number is valid.
  • Write a program that receives a credit card number and checks using the above rule whether the credit card number is valid.

Leave a Reply

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

You cannot copy content of this page