It’s Festive Season! Enjoy 30% Off

Use code FESTIVE30 at checkout

Code has been added to clipboard!

C++ String: Diving Deep

Reading time 2 min
Published Sep 3, 2019
Updated Sep 27, 2019

TL;DR – C++ strings are objects that represent sequences of characters. They're considered the driving force of coding in C++.

What are C++ Strings?

A C++ string is a one-dimensional array of characters that ends with a null character \0. You define a string with the following syntax:

Example
using namespace std;

int main() {
    char str[] = "C++";
}

Here is a basic example of a C++ string:

Example
using namespace std;

int main () {
   char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
}

In this case, a string consists of the different letters that make up the word 'Hello'. If you initialize the array, that is exactly the output you will get.

String Length

To find the length of a string in C++, you can use the size() or length() functions. Below is an example of how to accomplish just that.

Example
#include <iostream>

using namespace std;

int main() {
    string str = "C++ Programming";

    // str.length() can also be used
    cout << "String Length = " << str.size();
}
Theory is great, but we recommend digging deeper!

Defining a Class in C++

C++ is an object-oriented programming language. To learn how to create a string as an object that holds several strings, look at the example below:

Example
#include <iostream>

using namespace std;

int main() {
    // String object declared
    string str;
    cout << "Enter a string: ";
    getline(cin, str);

    cout << "You entered: " << str << endl;
}

Once a string is declared, it’s asked by the user. Using this method, there’s no length cap.

C++ String: Useful Tips

  • Use c_str() instead of toCharArray() when you need to call the send() function. This will prevent duplication of the string.
  • Pass string objects by as references rather than values. The code will be much more efficient as it won’t copy a string, but just reference it.
  • Initialize strings from Flash to save RAM by only loading the data when the string is loaded. Simply add 'F' before your body.