OneBite.Dev - Coding blog in a bite size

Cut A String In C++

Code snippet for how to Cut A String In C++ with sample and detail explanation

In this article, we will delve into how to cut a string in C++. This is a fairly straightforward process but needs to be understood completely for manipulating string efficiently in this high-level programming language.

Code Snippet

The cutting of strings in C++ quite often occurs within the context of string parsing where given strings are divided into smaller parts. Below is a simple code slice that demonstrates how to cut a string in C++:

#include <iostream>
#include <string>

int main() {
    std::string s = "Hello, World!";
    std::string sub = s.substr(0, 5);
    std::cout << sub << std::endl;
    return 0;
}

Code Explanation

This code simply defines a string s as "Hello, World!" and then creates another string sub that consists of a substring of s. The method substr() is used to cut the string s.

In the substr() function, the first parameter is the starting position, and the second parameter is the length of the substring you want to create. Here we start from position 0 and take a length of 5, that’s why our substring sub will be equal to “Hello”.

Now let’s break down the above code:

  1. #include <iostream> and #include <string>: These two essential lines include necessary libraries for our code to work; iostream for input-output operations and string to work with strings.

  2. int main(): This is the main function where the program starts execution.

  3. std::string s = "Hello, World!";: This line creates a string s and initializes it with the value “Hello, World!“.

  4. std::string sub = s.substr(0, 5);: Here, we create another string sub which is a substring of s. Substring starts from 0th index (inclusive) and has a length of 5 characters.

  5. std::cout << sub << std::endl;: This line simply prints our substring sub to the console.

  6. return 0;: This indicates that our program ran successfully.

The output of the code snippet will be: Hello

Obviously, you can adjust the parameters of substr() function to cut the string as per your requirements in your programs.

c-plus-plus