C++ Strings


What Are Strings in C++?

In C++, a string is a sequence of characters used to store and manipulate text. For example, a person’s name, a sentence, or any combination of letters, numbers, and symbols can be stored as a string.

C++ provides two main ways to handle strings:

  1. Using C-style strings (character arrays).

  2. Using the string class from the Standard Template Library (STL).

Most modern C++ programs use the STL string class because it’s simpler and more powerful than the traditional C-style character arrays.

Declaring and Initializing Strings in C++

1. Using the string class (Recommended)

To use strings in this way, include the <string> header.

Example:

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

int main() {
    string name = "Priya";
    cout << "Hello, " << name;
    return 0;
}

Output:

Hello, Priya

Here, string is a class, and name is an object that holds text.

2. Using C-style Character Arrays

This older method stores characters in an array that ends with a null character (\0).

Example:

#include <iostream>
using namespace std;

int main() {
    char name[] = "Priya";
    cout << "Hello, " << name;
    return 0;
}

Both methods work, but using string from the STL is more convenient because it has built-in functions for manipulation.

Taking String Input from the User

When you use cin to take input for a string, it only reads one word. If you want to read a full line with spaces, use getline().

Example using cin:

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

int main() {
    string name;
    cout << "Enter your name: ";
    cin >> name;
    cout << "Hello, " << name;
    return 0;
}

If the user types “Priya Sharma,” only “Priya” will be read.

Example using getline():

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

int main() {
    string fullname;
    cout << "Enter your full name: ";
    getline(cin, fullname);
    cout << "Hello, " << fullname;
    return 0;
}

Output:

Enter your full name: Priya Sharma
Hello, Priya Sharma

getline() reads the entire line including spaces until the Enter key is pressed.

String Operations in C++

The string class provides various functions to manipulate text easily.

1. Concatenation (Joining Strings)

You can combine two strings using the + operator or the append() function.

Example:

string first = "Priya ";
string last = "Sharma";
string fullname = first + last;
cout << fullname;

Or:

first.append(last);
cout << first;

Output:

Priya Sharma

2. Finding String Length

To find the number of characters in a string, use the .length() or .size() function.

Example:

string city = "Mumbai";
cout << "Length: " << city.length();

Output:

Length: 6

3. Accessing Individual Characters

Each character in a string has an index number starting from 0. You can access characters using square brackets [].

Example:

string word = "Hello";
cout << word[0];  // Prints H

You can also modify a character:

word[0] = 'J';
cout << word;  // Prints Jello

4. Comparing Strings

You can compare two strings using ==, !=, <, >, or the .compare() function.

Example:

string a = "Apple";
string b = "Banana";

if (a == b)
    cout << "Strings are equal";
else
    cout << "Strings are not equal";

Output:

Strings are not equal

The .compare() method returns:

  • 0 if both strings are equal,

  • A positive number if the first string is greater,

  • A negative number if the second string is greater.

5. Substrings

To extract a portion of a string, use the .substr() function.

Syntax:

string substr (size_t pos, size_t length);

Example:

string text = "C++ Programming";
cout << text.substr(4, 11);

Output:

Programming

6. Replacing Part of a String

The .replace() function replaces a part of the string with another string.

Example:

string message = "I like Java";
message.replace(7, 4, "C++");
cout << message;

Output:

I like C++

7. Inserting Text into a String

You can use .insert() to add text at a specific position.

Example:

string greeting = "Hello World";
greeting.insert(5, ", C++");
cout << greeting;

Output:

Hello, C++ World

8. Removing Characters from a String

The .erase() function removes part of a string.

Example:

string word = "Programming";
word.erase(3, 5); // removes "gram"
cout << word;

Output:

Proing

9. Finding a Character or Word in a String

The .find() function searches for a substring or character and returns its index.

Example:

string sentence = "Learn C++ Programming";
int pos = sentence.find("C++");
cout << "Found at position: " << pos;

Output:

Found at position: 6

If the substring is not found, .find() returns string::npos.

Converting Between Strings and Numbers

You can convert numbers to strings using to_string() and convert strings to numbers using functions like stoi() or stof().

Example:

int num = 123;
string text = to_string(num);
cout << "Number as string: " << text << endl;

string price = "99.99";
float value = stof(price);
cout << "String as float: " << value;

Output:

Number as string: 123
String as float: 99.99

Iterating Through Strings

You can use a loop to go through each character in a string.

Example:

string name = "C++";
for (int i = 0; i < name.length(); i++) {
    cout << name[i] << " ";
}

Output:

C + +

Summary of C++ Strings

Strings in C++ make it easy to work with text and user input. You can create, read, modify, and compare strings using simple functions like length(), append(), substr(), and find(). The STL string class provides flexibility and safety compared to traditional C-style arrays. Whether you’re working with user names, file paths, or text data, mastering strings is a vital part of learning C++ programming.


Practice Questions

  1. What is the difference between C-style strings and STL string in C++?

  2. How does the getline() function differ from cin when reading input?

  3. Which functions are used to find the length of a string in C++?

  4. What does the .append() function do in C++ strings?

  5. How can you compare two strings in C++?

  6. Write a program to input a user’s full name and print it on the screen.

  7. Write a program to concatenate two strings entered by the user.

  8. Write a program to find and replace a word in a string.

  9. Write a program to count the number of vowels in a given string.

  10. Write a program to extract a substring from the string “Programming in C++”.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top