Understanding Substrings in C++

Filed Under: C++
substrings in C++

In this article, we’ll take a look at how we can understand using Substrings in C++.

Often, there are a variety of cases where we would want to extract a particular pattern from a string.

In raw C, we would need to manually extract them ourselves. However, the C++ standard library gives us an easy to use function for such a scenario.

Let’s see how we can use this function, using illustrative examples!


C++ Substring – Basic Syntax

We can extract sub-strings using the substring function in C++. This is a part of the <string> header file, so we must include it.

The syntax of this function is as follows:

#include <string>

std::string substr(size_t pos, size_t len) const;

This function takes two parameters, pos and len.

Here, pos represents the start index for the sub-string, starting from 0.

Similarly, len represents the length of the sub-string. So essentially, we look at the string original_string[pos] to original_string[pos+len-1].

It will return the corresponding string object.

However, if pos = strlen(original_string), this will only return an empty string, since string[last_pos] = ‘\0’ (empty)!

And if pos > strlen(original_string), we get an out_of_range Exception.

To understand this better, let’s look at some examples.


Using substrings in C++ – Some Examples

Let’s first take a simple case, where we will directly get the substring (first 5 characters) of the below string:

“Hello from JournalDev”

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

int main ()
{
  string original_string = "Hello from JournalDev";

  // We want string[0:4] using substr()
  string substring = original_string.substr(0,5);

  cout << original_string << '\n';
  cout << substring << '\n';

  return 0;
}

Output

Hello from JournalDev
Hello

Indeed, we were able to get the correct substring!

Let’s look at one more example, for print a substring after a given match.

We will print the substring starting from the first character, until we find a match string (“–“)

We can use the find() function for our task, along with substr()

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

int main ()
{
  string original_string = "Hello from -- JournalDev";

  // Let's find the position of "--" using str.find()
  int position = original_string.find("--");

  // We'll get the substring until this pattern
  string substring = original_string.substr(0, position);

  cout << original_string << '\n';
  cout << substring << '\n';

  return 0;
}

Output

Hello from -- JournalDev
Hello from 

We were able to match the substring until the given pattern!

Let us look at one more example, where pos > strlen(original_string).

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

int main ()
{
  string original_string = "Hello from JournalDev";

  // Since 90 > strlen(original_string) = 24, this will raise an Exception
  string substring = original_string.substr(90, 100);

  cout << original_string << '\n';
  cout << substring << '\n';

  return 0;
}

Output

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::substr: __pos (which is 90) > this->size() (which is 24)
[1]    236 abort (core dumped)  ./a.out

Since the starting position pos is greater than the length of the original string, we get an out_of_range exception.

So be careful whenever you’re using str.substr(), and always ensure that you check the length of the string, or be prepared to handle the exception!


Conclusion

In this article, we learned about using the substring member function in C++.

For similar content, do go through our tutorial section on C++ programming!

References


Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages