1.2.2 Strings and Characters
The first data type we will explore are strings and characters. In the last lesson, you saw the basic use of the string variables. Strings are used in a similar fashion to languages such as Java, but there are a few differences worth noting.
Strings
A string is a series of characters stored in C++. While strings are included in the standard library, they are not automatically included. To use strings, you need to have either a string
include or an iostream
include since the iostream
library already imports strings.
Like other languages, you will use both string literals and string variables. String literals are defined using double quotes "
. String variables are declared with a lowercase string
definition. You can either declare a variable by itself, or declare and initialize in one statement:
Strings Are Mutable
Strings are mutable, which means they can be modified without being overwritten, which is different from languages such as Java.
While you will not see a lot of string exercises in this course, it is important to note that there are more string commands available compared to languages that have immutable strings. For example, if we want to insert a word into the middle of a string, we can do it with a command such as:
String Functions
Here is the syntax for some of the basic string functions. These functions are similar to what you will find in most computer languages.
str.substr(index)
Take a substring from the index to the end of the string
str.substr(index, length)
Take a substring from the index for the specified length
str.insert(index, string)
Insert a string at a given index position
str.length()
Return the length of a string
str[index]
or str.at(index)
Return the char
at index
Similar to most computer languages, strings are zero indexed, which means the first character is located at index 0.
One thing to note is that the substring is different from Java. In Java, you specify the start and end index value, but in C++ you specify the starting point and the length of the substring.
Characters
Characters represent a single letter, digit, or symbol and are used similar to other languages:
Characters are declared with the keyword
char
Characters are defined using single quotes
'
As mentioned above, you can extract a character from a string using one of two ways, str[index]
or str.at(index)
. If you use a valid index value, both return the same character.
If you attempt to access an invalid index, you will get different results. Using the .at()
function will return an error for an invalid index. Using the [ ]
will not crash your program, but will return a garbage value from something left in memory if the index is not valid.
As you explore C++ further, you will find this pattern. C++ has fewer checks than a language like Java, which means your program may not crash as much, but you will get bad values if you are not careful.
Try This Example
Last updated