C++ / C++ Arrays and Strings

String Manipulation Techniques

This tutorial will explore different techniques to manipulate strings in C++. You will learn how to use built-in functions to process and format strings.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores working with arrays, multi-dimensional arrays, and string manipulation.

String Manipulation Techniques in C++

1. Introduction

In this tutorial, you'll learn how to manipulate strings in C++. C++ provides a variety of built-in functions that allow us to process and format strings effectively.

By the end of this tutorial, you'll be able to:

  • Understand the basic concepts of string manipulation.
  • Use built-in string functions to manipulate strings.
  • Implement these techniques in your own programs.

Prerequisites: Basic knowledge of C++ is required. Familiarity with data types, particularly strings, would be beneficial.

2. Step-by-Step Guide

C++ strings are stored as a collection of characters. This allows us to perform various operations on them, like concatenation, comparison, and more.

Let's dive into some of the common string manipulation techniques.

2.1 Concatenation

Concatenation in C++ is done using the + operator.

string str1 = "Hello";
string str2 = "World";
string str3 = str1 + " " + str2;  // Concatenation
cout << str3;  // Outputs: Hello World

2.2 Comparison

C++ allows us to compare strings using the == (equality) and != (inequality) operators.

string str1 = "ABC";
string str2 = "ABC";
if (str1 == str2) {
    cout << "Strings are equal.";  // This will be printed
} else {
    cout << "Strings are not equal.";
}

2.3 Substring

We can extract a substring from a string using the substr() function. It takes two parameters: the starting index and the length of the substring.

string str = "Hello, World!";
string sub = str.substr(7, 5);  // Get substring starting from index 7 and of length 5
cout << sub;  // Outputs: World

Remember, string indices start from 0 in C++.

3. Code Examples

Let's look at some practical examples.

3.1 String Length

This example shows how to find the length of a string.

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

int main() {
    string str = "Hello, World!";
    cout << "Length of string is " << str.length();  // Outputs: Length of string is 13
    return 0;
}

3.2 String Replacement

This example shows how to replace a part of the string.

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

int main() {
    string str = "Hello, World!";
    str.replace(7, 5, "C++");  // Replace 'World' with 'C++'
    cout << str;  // Outputs: Hello, C++!
    return 0;
}

4. Summary

In this tutorial, we've covered basic string manipulation techniques in C++, including concatenation, comparison, and substring extraction. Practice these techniques to get a better grip on them.

As a next step, you can explore more advanced string manipulation techniques and built-in functions in C++. You can refer to the C++ documentation for more details.

5. Practice Exercises

  1. Write a program that concatenates two strings input by the user.
  2. Write a program that compares two strings to check if they are equal.
  3. Write a program that extracts a substring from a given string.

Here are the solutions for the exercises:

  1. Concatenation:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1, str2;
    cout << "Enter first string: ";
    cin >> str1;
    cout << "Enter second string: ";
    cin >> str2;
    string result = str1 + str2;
    cout << "Result: " << result;
    return 0;
}
  1. Comparison:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1, str2;
    cout << "Enter first string: ";
    cin >> str1;
    cout << "Enter second string: ";
    cin >> str2;
    if (str1 == str2) {
        cout << "Strings are equal.";
    } else {
        cout << "Strings are not equal.";
    }
    return 0;
}
  1. Substring:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string str;
    int start, length;
    cout << "Enter a string: ";
    cin >> str;
    cout << "Enter starting index and length for substring: ";
    cin >> start >> length;
    string sub = str.substr(start, length);
    cout << "Substring: " << sub;
    return 0;
}

Remember to keep practicing and experimenting with different scenarios. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help