Strings in C++
Sounds like a new term but believe me, we already used strings several times!
Let's see the 'Hello World' Program.
Here "Hello World"
is a string itself! C++ strings are sequences of characters used to represent textual data in programming. For example, the string "Hello World"
consists of the following characters: 'H'
, 'e'
, 'l'
, ... etc.
Properties of Strings
- We use double quotes to represent strings.
- It can consist of any characters like lowercase alphabets (a, b, c...), uppercase alphabets (A, B, C...), numbers (1, 2, 3...), symbols(&, *, -, _, ...) and even space.
- String characters can be accessed using indices similar to that of an array.
- String requires special sequences to print some special characters like
"
.
Create Strings
Now we'll see how can we create these strings in C++ programming. Strings are created using string
keyword just like int
for integer, char
for characters etc. Let's see a program to create and print a string to understand it more clearly.
Output
"
in a string
Suppose I want to create and print a string:
Joey said "How you doing?"
Let's try writing a program for this:
Output
The program produces an error! But why?
This is because we have used "
inside a string. Since double quotes are used to enclose a string, we can't use them inside it.
But Joey said what he said! I need to print that without any error 😭
Let's see how can we achieve this!
Escape Sequences
Since there are quotation marks in it, we have to use \"
to indicate "
. The code will change as:
Output
Here \"
is called an escape sequence as it allows us to add special characters like "
in strings!
\n
in a string
If you remember then \n
when added to any text wasn't printed but helped us to get a newline. This is because \n
is also an escape sequence!
Example
Output
Join Our Course

Offer ends in:
Days
Hours
Mins
Secs