Lesson 9 - Strings in the C++ language
In the previous exercise, Solved tasks for C++ lessons 8, we've practiced our knowledge from previous lessons.
Lesson highlights
Are you looking for a quick reference on strings and string functions in C++ instead of a thorough-full lesson? Here it is:
Getting and setting the character at a given position:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string greeting = "Hello ICT.social";
cout << greeting << endl;
greeting[0] = 'h'; // change the first character
cout << greeting << endl;
cout << greeting[2] << endl; // print the 3rd character
return 0;
}
Reading text with spaces from the console
using getline()
:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string name;
cout << "Enter your name: ";
getline(cin, name);
cout << "Hello " << name << endl;
cin.get();
return 0;
}
Searching for a substring:
#include <string>
#include <iostream>
using namespace std;
int main()
{
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();
return 0;
}
Using string functions:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string greeting = "Hello ICT.social";
cout << "Length: " << greeting.length() << endl;
cout << "Substring: " << greeting.substr(6, 10) << endl;
string concatenated = greeting + " world!";
cout << "Concatenated strings: " << concatenated << endl;
greeting.clear();
cout << "Cleared: " << greeting << endl;
cout << "Alpha before Bravo: " << ("Alpha" < "Bravo") << endl;
return 0;
}
Would you like to learn more? A complete lesson on this topic follows.
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:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string greeting = "Hello ICT.social!";
greeting[0] = 'h';
for (int i = 0; i < 17; i++ )
cout << greeting[i] << ' ';
cout << endl;
cin.get();
return 0;
}
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:
#include <string>
#include <iostream>
using namespace std;
int main()
{
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Hello " << name << endl;
cin.ignore(0xFF,'\n');
cin.get();
return 0;
}
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).
#include <string>
#include <iostream>
using namespace std;
int main()
{
string name;
cout << "Enter your name: ";
getline(cin, name);
cout << "Hello " << name << endl;
cin.get();
return 0;
}
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).
#include <string>
#include <iostream>
using namespace std;
int main()
{
string greeting = "Hello ICT.social";
int length = greeting.length();
cout << length;
return 0;
}
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.
#include <string>
#include <iostream>
using namespace std;
int main()
{
string firstGreeting = "Hello ";
string secondGreeting = "World";
string greeting = firstGreeting + secondGreeting;
cout << greeting;
return 0;
}
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.
#include <string>
#include <iostream>
using namespace std;
int main()
{
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();
return 0;
}
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 occurrencefind_first_of()
: finds the first occurrence of any character of the parameterfind_last_of()
: finds the last occurrence of any character of the parametersubstr()
: returns a substring defined by a starting position and a length
Comparing strings
We can compare 2 strings alphabetically using the >
and
<
operators.
#include <string>
#include <iostream>
using namespace std;
int main()
{
string first = "Hello";
string second = "World";
bool before = first < second;
cout << before;
return 0;
}
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 string
s 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 string
s. These
interpretations come from the C language (because C doesn't have
string
s), 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 Strings
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.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 1x (1.25 MB)
Application includes source codes in language C++