Unraveling the Magic of C++ Strings for Beginners: A Comprehensive Guide - w9school

Dive into the world of C++ strings with our beginner-friendly guide! Learn the basics, manipulation techniques, and unleash the power of strings effortlessly. Happy coding!

 Unraveling the Magic of C++ Strings for Beginners: A Comprehensive Guide - w9school

Welcome to the exciting world of C++ programming! If you're just getting started in programming, learning the fundamentals is vital. In this blog, we'll explore C++ strings - a foundational component used by many programs that enables manipulation and handling of textual data. Don't worry though; our straightforward explanation of this topic ensures even those without technical backgrounds can follow along easily!

Understanding Strings in C++:

Strings, in C++, are sequences of characters which could include letters, numbers, symbols or even spaces. You could think of strings as strings of letters strung together to form words or sentences which your program needs to interpret.C++ makes string manipulation simple with the string class from its Standard Template Library (STL). This class offers many functions and methods to make string manipulation straightforward. Unlike some other programming languages, C++ doesn't come equipped with its own string data type - instead relying on external services for string manipulation such as this string class from STL.

C++ Strings

Strings are used to store text.

String Variables:

A strings variable is made up of characters, surrounded with double quotation marks:

Example

Create a variable kind strings and assign the following value:

string greeting = "Hello";

To make use of strings, you have to include a header file within the source code. This is the library:

Example

// Include the string library
#include 

// Create a string variable
string greeting = "Hello";

String Concatenation

It is possible to use the + operator can be applied to strings to join them to create the new string. This is known as concatenation:

Example

string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;

In the above example we put a space before firstName to create an empty space between John Doe and John Doe in the output. You could, however, include a space using quotes ( " " or " " or):

Example

string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;

Append

Strings within C++ is actually an object that contains functions that perform specific actions on strings. For instance, you can also combine strings with appsend(). append() function:

Example

string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;

Adding Numbers and Strings

WARNING!

C++ uses the + operator to perform as well addition as well as concatenation.The numbers are added. 

Strings are grouped together.

If you multiply two numbers and the result is the following number:

Example

int x = 10;
int y = 20;
int z = x + y;      // z will be 30 (an integer)

If you are able to add two strings and the result is the string concatenation

Example

string x = "10";
string y = "20";
string z = x + y;   // z will be 1020 (a string)

If you attempt adding a number the string, you will encounter an error:

Example

string x = "10";
int y = 20;
string z = x + y;

C++ String Length

String Length

To determine an estimate of the string's length utilize length(): length() function:

Example

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();

Tips: You might see certain C++ programs that utilize the size() function to determine the length of an unicode string. This is simply an alias for length(). It's your choice if you choose to utilize length() or size():

Example

string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();

C++ Access Strings

Access Strings

You can find the characters contained in strings by using its index number in the square brackets [].

This example shows only the the first line of myString:

Example

string myString = "Hello";
cout << myString[0];
// Outputs H

NOTE:String indexes start with the number 0: [0] represents the initial character. "1" is the 2nd character, and so on.

This example shows this example with the 2nd characters within myString:

Example

string myString = "Hello";
cout << myString[1];
// Outputs e

Change String Characters

To alter the meaning of a certain part of a string use the index number and then use single quotes:

Example

string myString = "Hello";
myString[0] = 'J';
cout << myString;
// Outputs Jello instead of Hello

C++ Special Characters

Strings - Special Characters

Since strings must be written in the quotes C++ will not understand the string and produce an error:

Example

string txt = "We are the so-called "Vikings" from the north.";

The best way to avoid this issue is to utilize to use the Backslash Escape character.

Backslash ( \) escape character transforms characters to string:

Escape character Result Description
\' ' Single quote
\" " Double quote
\\ \ Backslash

The sequence \" inserts a double quote inside a string:

Example

string txt = "We are the so-called \"Vikings\" from the north.";

The sequence "\'" introduces a single quotation mark in the string:

Example

string txt = "It\'s alright.";

The sequence "\\" introduces one backslash into the string:

Example

string txt = "The character \\ is called backslash.";

Other characters that are popular escape characters that are available in C++ are:

Escape Character Result
\n New Line
\t Tab

C++ User Input Strings

User Input Strings

There is a way to utilize extract operator >> on cin to save a string that is entered by the user:

Example

string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;

// Type your first name: John
// Your name is: John

In reality, cin considers spaces (whitespace tabs, whitespace) as an ending character, which means it is able to hold only one word (even even if you type several words):

Example

string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;

// Type your full name: John Doe
// Your name is: John

In the previous example you'd expect that the program would print "John Doe", but it prints "John".
This is why whenever working with string we typically employ the getline() function to read a text line. It requires the character cin for the initial parameter as well as the string variable in the second:

Example

string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;

// Type your full name: John Doe
// Your name is: John Doe

C++ String Namespace

Omitting Namespace

You may see C++ programs that can be run without the standard namespace library. The namespace line that uses the namespace is omitted and replaced by the std keyword which is followed by the operator for strings (and the cout) objects:

Example

#include 
#include 

int main() {
  std::string greeting = "Hello";
  std::cout << greeting;
  return 0;
}

It's up to you whether you wish to use the namespace library that is standard or not.

Test Yourself with C++ Exercises 

If you are ready to take test upon what what you've learnt then Click Here

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow