C++ Strings

What is a String?

In C++, strings are objects of the string class.

They are easier and safer than C-style character arrays.

Loading...
Output:

Printing Strings

Loading...
Output:

Accessing Characters

Use indexing to access characters.

Loading...
Output:

String Length

Use .length() or .size().

Loading...
Output:

Modifying Strings

Loading...
Output:

Substring

Extract part of a string using substr().

Loading...
Output:

String Input

Use getline() to read full lines.

Loading...
Output:

Comparing Strings

Loading...
Output:

Full Example

Loading...
Output:

Why Strings are Important

  • Used for text processing
  • Safer than C-style strings
  • Common in real applications

Common Mistakes

  • Forgetting #include <string>
  • Using cin instead of getline
  • Mixing C-style and C++ strings

Practice

Create a string, modify it, and print its length and substring.

Loading...
Output:

Need Help?