Lesson 8 - Strings in the C++ language

C and C++ C++ Basics Strings in the C++ language

We've already encountered strings in this course. We read and wrote them using a variable of the string data type. There are multiple ways to work with strings in C++. We'll introduce the simplest one in today's tutorial which are static strings, represented by the string type.

The string library

Consider that we want to store the text "Hello ICT.social" in a variable. In that case, we'd simply create an object of the string type and assign the string to it. We don't have to deal with the fact that we don't know what an object is. We'll get into all of that in the OOP in C++ course. However, we will have to include the string header file:

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

int main()
{
        string greeting = "Hello, ICT.social!";
        cout << greeting << endl;
        cin.get();
        return 0;
}

As we've already seen a couple of times in C++, the text will be printed to the console and the program will wait for the user to press Enter.

Console application
Hello, ICT.social!

Working with single characters

We can work with strings as with arrays since they really are arrays internally :) Therefore, we're able to print the first character or change the characters. It's a good idea to use predefined string functions for other sorts of string manipulations. We'll introduce the most important ones at the end of this lesson.

For now, let's try to change the first character and print the text with spaces between the letters:

string greeting = "Hello ICT.social!";
greeting[0] = 'h';
for (int i = 0; i < 17; i++ )
        cout << greeting[i] << ' ';
cout << endl;
cin.get();

The result:

Console application
h e l l o I C T . s o c i a l !

By changing the first character to 'h' we made the first letter lowercase. Thanks to the brackets, we were then able to access single characters of the string and print them separated by spaces.

Reading/writing strings

We can read or write strings just like we're used to. We use the cin object to do so. We declare the variable that is to be read as a string.

The following program will let you enter your name and it'll greet you:

string name;
cout << "Enter your name: ";
cin >> name;
cout << "Hello " << name << endl;
cin.ignore(0xFF,'\n');
cin.get();

The result may surprise you:

Console application
Enter your name: David Capka Hello David

Notice that only the first word has been read. Reading inputs using cin will terminate with the first white character. White characters are characters that can't be printed, e.g. spaces, enters, or tabs. Also notice the line with cin.ignore(0xFF,'\n'). This line specifies that all text which is waiting in the input buffer should be ignored until it encounters the '\n' character which stands for enter. If we didn't call that method, cin.get() would automatically read the rest of the name in the buffer queue and the application wouldn't wait for the user's input and end immediately.

If we wanted to read the whole line, we'd use the getline() function which takes the cin object as the first parameter and a string variable as the second parameter (the data will be stored in this string).

string name;
cout << "Enter your name: ";
getline(cin, name);
cout << "Hello " << name << endl;
cin.get();

Standard string functions

The string type provides a range of pre-made functions for us which will simplify our applications.

length()

We can determine a string's length using the length() method (we'll cover the differences between functions and methods later on in the object-oriented course).

string greeting = "Hello ICT.social";
int length = greeting.length();
cout << length;

clear()

If we wanted to clear the space occupied by a string, we'd use the clear() method. This method erases all of the content stored in a string variable.

string greeting = "Hello ICT.social";
greeting.clear();

String concatenation

We can join 2 strings into a single one using the "+" operator as we're used to doing with arithmetic operations.

string firstGreeting = "Hello ";
string secondGreeting = "World";
string greeting = firstGreeting + secondGreeting;
cout << greeting;

find()

We are able to search for a character or a substring in a string. C++ will search through it from beginning to end and if it finds the character or the substring, it returns its position. If the string doesn't contain what we're looking for, a value greater than the last index is returned.

string text = "Mr X stroke again.";
int position = text.find("oke");
if (position < text.length())
        cout << "Found at position " << position << endl;
else
        cout << "Not found" << endl;
cin.get();

As you may have guessed, the index is zero-based.

Console application
Found at position 8

String also provides a set of similar methods with slightly different functionality:

  • rfind(): finds the last occurrence
  • find_first_of(): finds the first occurrence of any character of the parameter
  • find_last_of(): finds the last occurrence of any character of the parameter
  • substr(): returns a substring defined by a starting position and a length

Comparing strings

We can compare 2 strings alphabetically using the > and < operators.

string first = "Hello";
string second = "World";
bool before = first < second;
cout << before;

There are some more string methods which we'll get familiar with further along the way.

Alternative string interpretations

C++ also provides support for low-level string declaration. Meaning that it allows us to define strings as plain char arrays instead of string type instances. The string type in C++ is only a wrapper and uses the aforementioned low-level access internally. If you work with C libraries or you need to call system routines, you'll have to use char arrays instead of strings. These interpretations come from the C language (because C doesn't have strings), so you can read all about it there. The basic description can be found in the Strings in the C language lesson, and the topic continues in String in the C language - working with single characters.

That'd be all for today. In the next lesson, Strings in C++ - Working with single characters, we'll continue learning about strings and use our knowledge on a couple of sample applications.


 

  Activities (4)

Article has been written for you by David Capka
Avatar
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College Author learned IT at the Unicorn College - prestigious college providing IT and economical education.

Do you like this article?
Nobody has rated this just yet, be the first one!


 


Thumbnail
Previous article
Arrays in the C++ language
Thumbnail
All articles in this section
C++ basic constructs

 

 

Comments

To maintain quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it is free.

Nobody has commented yet - be the first!