Checking Whether a String Starts with Another String in C++

Posted on In Programming, QA, Tutorial

In many text processing tasks, we often need to check if a given string starts with a specific substring. In this article, we will demonstrate how to achieve this using the std::string::compare() function from the C++ Standard Library.

The compare() function has several overloads, but the one of interest for our purpose is:

int compare(size_type pos1, size_type count1, const basic_string& str) const;

To check if a string starts with another string, we can call the compare() function on the first string, with pos1 set to 0, count1 as the length of the second string, and str as the second string. If the function returns 0, it means the strings match at the specified positions.

Here’s a complete example demonstrating how to use the compare() function to check whether a string starts with another string:

#include <iostream>
#include <string>

bool startswith(const std::string& str, const std::string& cmp) {
  return str.compare(0, cmp.length(), cmp) == 0;
}

int main () {
  std::cout << std::boolalpha; // To display true/false instead of 1/0
  std::cout << "startswith(\"big string here...\", \"big\") -> " << startswith("big string here...", "big") << std::endl;
  std::cout << "startswith(\"big string here...\", \"small\") -> " << startswith("big string here...", "small") << std::endl;
  std::cout << "startswith(\"big\", \"big string here\") -> " << startswith("big", "big string here") << std::endl;

  return 0;
}

The output of the example will be:

$ g++ -std=c++20 cpp-start-with.cpp -o s && ./s
startswith("big string here...", "big") -> true
startswith("big string here...", "small") -> false
startswith("big", "big string here") -> false

In summary, the std::string::compare() function provides an efficient and straightforward way to check whether a string starts with another string in C++. By using the appropriate parameters, we can easily determine if two strings match at the specified positions, making this function highly useful for various text processing tasks.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

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