Course Content
C++ Data Types
3. Other Data Types and Type Convesion
C++ Data Types
Working with two Strings
This chapter explains how to compare, copy, and swap strings.
Let's start with
Comparing strings
You can compare strings using the ==
or !=
operators.
Those operators work pretty much as expected. One thing to note is that they are case-sensitive, so "Code"
is not equal to "code"
.
main.cpp
There are also <
, <=
, >
, and >=
operators for strings.
They compare strings by their length first.
If lengths are equal they compare the characters of the strings based on their ASCII values.
main.cpp
Copying
To copy the string, just use the assignment operator (=
):
Here is an example:
main.cpp
Swapping
You can swap the values of two strings using the .swap()
method with the following syntax:
Here is an example:
main.cpp
Task
Ensure a string named shorter
is shorter than longer
.
If it's not true, swap their values.
Everything was clear?