C++ Strings

What is a String in C++?

A string is just a bunch of characters joined together—like words or sentences. 📦

In C++, you can use strings in two ways:

  • C-style strings – old-school character arrays
  • C++ string class – modern and easy to use

🎩 1. C-style Strings (Character Arrays)

These are arrays of characters ending with '\0' (null character).

char name[] = "Alice";

🔧 Example: C-style String

#include <iostream>
using namespace std;

int main() {
    char name[] = "Alice";
    cout << "Hello " << name << "!" << endl;
    return 0;
}
  

Try It Now

🚀 2. C++ Strings (string Class)

Use the string class from the <string> header — clean and simple!

#include <string>
string city = "Paris";

🔧 Example: C++ String Class

#include <iostream>
#include <string>
using namespace std;

int main() {
    string city = "Paris";
    cout << "Welcome to " << city << "!" << endl;
    return 0;
}
  

Try It Now

🧰 Some Handy String Functions

  • length() – count characters
  • append() – add more text
  • substr() – get a piece of the string

🔧 Example: Fun with Strings

#include <iostream>
#include <string>
using namespace std;

int main() {
    string greet = "Hello";
    greet.append(" World!");
    cout << greet << endl;
    cout << "Length: " << greet.length() << endl;
    cout << "Part: " << greet.substr(6, 5) << endl;
    return 0;
}
  

Try It Now

💡 Summary

  • Use char[] for basic strings, or string class for easier handling
  • string has cool built-in features: length, append, substr, etc.
  • Works great with cin, cout, and functions

Now you can string words together like a pro poet! ✨