0
0
C++programming~5 mins

String handling basics in C++

Choose your learning style9 modes available
Introduction

Strings let us work with words and sentences in programs. They help us store and change text.

When you want to greet a user by name.
When you need to read a sentence from the keyboard.
When you want to check if a word is inside a sentence.
When you want to join two words together.
When you want to count how many letters are in a word.
Syntax
C++
std::string variableName = "text";

// Common operations:
variableName.length();       // Get number of characters
variableName + "more";     // Join strings
variableName[i];             // Access character at position i
variableName.substr(start, length); // Get part of string

Use #include <string> to work with strings.

Strings start at position 0 for the first character.

Examples
Create a string named name with the text "Alice".
C++
std::string name = "Alice";
Get the number of letters in name and store it in len.
C++
int len = name.length();
Access the first letter of name, which is 'A'.
C++
char first = name[0];
Join " Smith" to the name to make a full name.
C++
std::string greeting = name + " Smith";
Sample Program

This program shows how to create a string, find its length, get the first letter, join another string, and get a part of the string.

C++
#include <iostream>
#include <string>

int main() {
    std::string word = "Hello";
    std::cout << "Word: " << word << "\n";
    std::cout << "Length: " << word.length() << "\n";
    std::cout << "First letter: " << word[0] << "\n";
    std::string newWord = word + " World";
    std::cout << "Joined string: " << newWord << "\n";
    std::cout << "Substring (1,3): " << newWord.substr(1,3) << "\n";
    return 0;
}
OutputSuccess
Important Notes

Remember strings count positions starting at 0, so the first letter is at position 0.

Use length() to find how many characters are in the string.

Joining strings with + creates a new string without changing the originals.

Summary

Strings store text like words and sentences.

You can find length, access letters, join strings, and get parts of strings easily.

Start practicing by creating strings and trying these operations yourself!