Skip to main content

Strings

Strings

Sounds like a new term but believe me, we already used strings several times!

Let's see the 'Hello World' Program.

#include <iostream>
using namespace std;
 
int main() {
 
    cout << "Hello World";
 
    return 0;
}
 

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.

#include <iostream>
using namespace std;
 
int main() {
    
    // create a string
    string word = "LearnYard";
  
    // print string
    cout << word;    // LearnYard
  
    return 0;
}

Output

LearnYard

" 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:

#include <iostream>
using namespace std;
 
int main() {
    
    string sentence = "Joey said "How you doing?"";
    cout << sentence;
 
    return 0;
}

Try on Compiler

Output

6:23: error: unable to find string literal operator ‘operator""How’ with ‘const char [11]’, ‘long unsigned int’ arguments
    6 |     string sentence = "Joey said "How you doing?"";
      |                       ^~~~~~~~~~~~~~~

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:

#include <iostream>
using namespace std;
 
int main() {
    
    string sentence = "Joey said \"How you doing?\"";
    cout << sentence;
 
    return 0;
}

Try on Compiler

Output

Joey said "How you doing?"

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

#include <iostream>
using namespace std;
 
int main() {
 
    string st = "Hello\nCoders\n:)";
    cout << st;
 
    return 0;
}

Try on Compiler

Output

Hello
Coders
:)