如何检查const char*是否以特定字符串开头?(C++)
How do I check if a const char* begins with a specific string? (C++)
我有一个const char*变量,我想检查它是否以某个字符串开头。
例如:
string sentence = "Hello, world!";
string other = "Hello";
const char* c = sentence.c_str();
if(/*"c" begins with "other"*/)
{
//Do something
}
如何使用if语句来完成此操作?
要检查C字符串是否以某个子字符串开头,可以使用strncmp()
。
对于C++字符串,有一个接受偏移量和长度的std::string::compare()
重载。
您可以使用c函数strstr(string1, string2)
,它返回一个指向字符串1中第一个出现的字符串2的指针。如果返回的指针指向字符串1,则字符串1以您想要匹配的内容开始。
const char* str1 = "Hello World";
const char* ptr = strstr(str1, "Hello");
// -----
if(str1 == ptr)
puts("Found");
请记住,您是其他变量,需要在strstr函数的上下文中使用它的.c_str()方法。
脑海中浮现出几个选项,一个使用遗留的C调用,另两个更特定于C++。
如果真的有一个const char *
,那么最好使用遗留的C,但是,由于您的示例代码只从std::string
创建了一个const char *
,我提供了其他解决方案,因为您似乎只使用字符串作为真正的data源。
因此,在C++中,您可以使用string::compare
或string::find
,尽管compare
可能更高效,因为它只在字符串的开头进行检查,而不是到处检查并将返回值与零进行比较(find
似乎更简洁,因此,如果您重视这一点,并且速度不是最重要的,则可以使用它):
if (haystack.compare(0, needle.length(), needle) == 0)
if (haystack.find(needle) == 0)
使用遗留的C东西,你可以做到:
if (strncmp (haystack.c_str(), needle.c_str(), needle.length()) == 0)
有关示例,请参阅以下完整程序:
#include <iostream>
#include <string>
#include <cstring>
int main (void) {
std::string haystack = "xyzzy";
std::string needle = "xy";
std::string other = "99";
if (haystack.compare(0, needle.length(), needle) == 0)
std::cout << "xy foundn";
else
std::cout << "xy not foundn";
if (haystack.compare(0, other.length(), other) == 0)
std::cout << "xx foundn";
else
std::cout << "xx not foundn";
return 0;
}
对于其他选项,只需更改上面显示的if
语句即可匹配给定的示例。
相关文章:
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 字符串开头的分隔符
- 如何使字符串出现在编译的二进制可执行文件的开头?
- 如何在 Arduino 字符串的开头添加元素.类似于 JS unshift();
- 为什么使用 QString::right 在字符串开头省略逗号?
- cout 切断 for 循环中的字符串开头
- 如何从字符串开头到第二个分隔符中提取子字符串?
- ZeroMQ (cppzmq) 订阅者,过滤器以相同的字符串开头
- 如何检查 std::vector<std::string> 的元素是否以某个子字符串开头?
- 如何在 qt 中使用 QRegularExpression 匹配字符串开头的空格?
- DeleteFile,以子字符串开头
- 是否有函数/WinAPI 可以判断一个字符串是否以不区分大小写的语言方式以另一个字符串开头?
- 检查一个字符串是否以另一个已知字符串开头
- 如何检查const char*是否以特定字符串开头?(C++)
- 字符串以某个字符串开头
- 如何清除字符串开头的垃圾
- 删除字符串c++开头和结尾的标点符号
- 检查字符串是否以另一个字符串开头:find或compare
- C++ std::map<std::string, int> 获取键以特定字符串开头的值
- c++ getline在字符串开头添加空格