| |

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

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.

Similar Posts

  • Setting Up VPN-like Network Between Several Clusters Using iptables

    It is common to connect servers with only internal IPs from several clusters. VPN is a common technique for this. With iptables, we can implement many functions of VPN with possibly higher performance. The slides here give a brief introduction to how to set up a VPN-like network between 2 clusters which connect to each…

  • MFC程序使用系统风格界面

    VC6默认编译出来的程序在XP下Luma风格下运行也是Windows的经典界面, 有损界面的美观与统一. VC2008默认设置下如果不是使用的unicode也是如此. 本文给出使VC6和VC2008可以编译出使用系统界面风格的解决方案. 1. 使VC6编译出使用系统风格的程序 步骤如下: 1) 创建一个.manifest文件的资源. 在res/文件夹下创建一个跟以程序名加.manifest的文件, 如果程序为test.exe, 则创建test.exe.manifest 文件可由此下载: https://www.systutorials.com/t/g/programming/resultcollector.manifest/ 注意要使用utf-8编码保存。 2) 将新定义的资源加入到.rc2文件中, 类型设为24. 打开res/文件夹下的.rc2文件, 在其中加入如下定义: 1 24 MOVEABLE PURE “res/test.exe.manifest” 其中的文件地址按1)步中修改的设置即可. 之后编译即可, 为了使程序界面可能充分利用系统的界面特性, 可以将界面字体设置为TrueType类型的, 利用Windows XP等系统的屏幕字体平滑特性. 2. 使VC2008编译出使用系统风格的程序 在VC2008下就比较简单了, 如果程序字符集使用unicode则默认就是使用系统界面风格的, 如果选择其它的类型, 则编辑下stdafx.h即可. 最后面部分找到这么一段: #ifdef _UNICODE #if defined _M_IX86 #pragma comment(linker,”/manifestdependency:”type=’win32′ name=’Microsoft.Windows.Common-Controls’ version=’6.0.0.0′ processorArchitecture=’x86′ publicKeyToken=’6595b64144ccf1df’ language=’*'””) #elif defined _M_IA64 #pragma comment(linker,”/manifestdependency:”type=’win32’…

  • How to set and get an environment variable in C on Linux?

    How to set and get an environment variable in C on Linux? You can use the setenv and getenv POSIX APIs to set and get environment variables. To add or change environment variable: #include <stdlib.h> int setenv(const char *envname, const char *envval, int overwrite); To get value of an environment variable: #include <stdlib.h> char *getenv(const…

  • How to Speed Up Firefox DNS Lookup in Linux

    How to speed Up Firefox DNS Lookup in Linux: 1. Close IPV6 support # echo “alias net-pf-10 off” >> /etc/modprobe.conf # echo “alias ipv6 off” >> /etc/modprobe.conf Type “about:config” into the address line and enter. Set “network.dns.disableIPv6” to “true” 2. Some other tweaks Type “about:config” into the address line and enter. Set “network.http.pipelining” to “true”…

  • Force Linux to reboot

    How to force Linux to reboot when the reboot command does not work. Enable the use of the magic SysRq option: # echo 1 > /proc/sys/kernel/sysrq Reboot the machine: # echo b > /proc/sysrq-trigger Even if you could not log on the system but sshd is working, you can force the Linux to reboot by:…

  • How to exclude directories with certain names from rsync on Linux?

    How to exclude directories with certain names like “cache” from rsync on Linux during backup? The “cache” directory may in many different paths, such as file1/cache/ or file2/cache/, and adding all “cache” directories to rsync command is not a doable way. You can use rsync with –exclude=cache/ like rsync -avxP –exclude=cache/ /path/to/src/directory/ /path/to/dst/dir/ Read more:…

Leave a Reply

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