Broad Network


C++ String Class Basics

String in C++ Standard Library Simplified - Part 1

Forward: In this part of the series, we look at C++ String Class Template in the standard library.

By: Chrysanthus Date Published: 25 Aug 2012

Introduction

This is part 1 of my series, String in C++ Standard Library, Simplified. In this part of the series, we look at an introduction to C++ String Class Template in the standard library.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

C++ Standard Library
C++ installation comes with a library that has important and common features (ready-made code segments) that you can use, without writing code for the features. This library is called the standard library. The library is divided into categories. These categories are still called libraries. The categories are divided into components. Components are divided into entities. Entities are basic things like data types and functions.

There are many header files for the standard library. You access a feature (entity) through a header file. With a typical C++ installation, you do not need to know where (directory) the standard library or standard libraries are kept; you do not need to even know where the header files for the standard library are kept. With my installation (mingw), all you need to know is the name of the header files. To use the header files, you just need to include it at the top of your code (without indicating the path). You do that using the #include preprocessing directive with the name of the header file alone in angle brackets.

How do you know which feature is in a header file. One way to know that is by reading articles, which are of reference nature like this one (series).

Prerequisite
There are other articles (tutorials) I have written in this blog on C++. You need to have read them or articles similar to them before reading this series. The titles of the articles or series in this blog, which are prerequisite to reading this series are:

- Getting Started with C++
- OOP Basics in C++
- C++ Function Templates
- Dynamic Objects in C++
- Integer and Float Object Types in C++
- Reference in C++
- Assignment Operators in C++
- Basics of Exceptions in C++
- User Types from Fundamental Types in C++
- An in-depth Look into C++ Core String

A computer language builds up. There are certain things you have to learn first and then use them to learn higher things. Each of the above titles is either a tutorial or the first tutorial in a series. If it is the first part of a series, then you should have read the whole series. If it is a tutorial standing alone, then you should have read the tutorial. To reach any of the articles, just type the title of the article and my name Chrys in the Search Box of this page and click Search.

String Classes
In the string component of the standard library, there are a number of related classes. In this series I will treat all the related classes as one class, called the string class. The string classes use the Free Store Memory (dynamic objects) and templates. You need to include the string header in your code file in order to access the string class features. Toward the end of the series, we shall use functions that are not of the string class, but are of the strings Library.

What I give you in this series is a simplified version of what is in the ISO/IEC 14882:2003 C++ specification. So I cover most of what is there.

You should be trying the code samples in this series as you go along, to see the results.

Instantiating a String
Two simple ways you can use to instantiate a string object from the string class are;

    string str;

and

    string str(“string text”);

where str is the identifier of the string object, you can give whatever name you want. The following code illustrates the use of the first method:

#include <iostream>
#include <string>
using namespace std;

int main()
    {
        string str;
        str = "Yes, I am the one.";
        cout << str;
    
        return 0;
    }

Note the include string header; you do this when you have to use any string method or operator. With the first syntax, after creating the string object, you can assign a string literal to the object identifier. You can also do initialization when creating the string as follows:

        string str = "Yes, I am the one.";

The following code illustrates how you can use the second syntax:

#include <iostream>
#include <string>
using namespace std;

int main()
    {
        string str("Yes, I am the one.");
        cout << str;
    
        return 0;
    }

Note: The string literal in quotes is a string whose content is constant (the region of each of the characters in the string is read-only).

String Capacity

Size of String
You can know the size of a string using the string member functions (methods), size() and length(). The return value, which is the number of characters, can be assigned to an int. The following code illustrates this:

#include <iostream>
#include <string>
using namespace std;

int main()
    {
        string str = "Yes, I am the one.";
        int strSize = str.size();
        cout << strSize<<"\n";
        int strlgth = str.length();
        cout << strlgth << "\n";
    
        return 0;
    }

Maximum Size
You can know the maximum size your string can have in your computer system using the string member function (method), max_size(). The return value can be assigned to an int, which refers to the number of characters. The following code illustrates this:

#include <iostream>
#include <string>
using namespace std;

int main()
    {
        string str = "Yes, I am the one.";
        int strMaxSize = str.max_size();
        cout << strMaxSize;
    
        return 0;
    }

Resizing a String
You can resize a string. If the new size is less than the original size, the string is truncated on the right side leaving characters on the left side. If the new size is bigger than the original size, then the character you will choose is padded at the end to make up the size. The new size should be less than or equal to maximum size (see above). The syntax for the string resize member function is:

    void resize(size_type n, charT c);

where n is the new size. The second parameter is optional; it is for the padded character. If you omit the second parameter, and if the new size is bigger than the old size, then the space character will pad the end of the string. The following code illustrates this:

#include <iostream>
#include <string>
using namespace std;

int main()
    {
        string str = "Yes, I am the one.";
        str.resize(25);
        cout << str <<"\n";
        str.resize(30, 'x');
        cout << str <<"\n";
        str.resize(10, 'x');
        cout << str <<"\n";
    
        return 0;
    }

The space between the sentence and x’s in the second output results from the spaces padded by the first output.

Know if a string is empty
The method, empty() of the string class can be used to know if a string is empty. The syntax is:

        bool empty() const;

You can use the string member function, empty() as in the following code:

#include <iostream>
#include <string>
using namespace std;

int main()
    {
        string str = "Yes, I am the one.";
        if (str.empty() == 1)
            cout << "Empty";
        else
            cout << "Not Empty";
   
        return 0;
    }

If you want to empty the above string, you can assign an empty string literal to it as follows:

    str = "";

Accessing a String Like an Array
You can use the array operator, [] with a string object. What goes inside the square brackets is the position number of the character in the string beginning from zero.  This position number should be less than the size of the string. So if you begin with the name of the string object, followed by the square brackets and inside the square brackets you have an integer that is less than the size of the string, the resulting expression will return the character at that position, similar to what happens with an array. The following code illustrates this:

#include <iostream>
#include <string>
using namespace std;

int main()
    {
        string str = "Yes, I am the one.";
        char myChar = str[8];
        cout << myChar;
        return 0;
    }

Your output of the above code should be, m, which is at position 8, counting from zero.

Well, let us take a break here and continue in the next part of the series.

Chrys

Related Courses

C++ Course
Relational Database and Sybase
Windows User Interface
Computer Programmer – A Jack of all Trade – Poem
NEXT

Comments

Become the Writer's Fan
Send the Writer a Message