C++ 如何在C++中检查字符串开始

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8095088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:59:16  来源:igfitidea点击:

how to check string start in C++

c++string

提问by sufyan siddique

Is there any way in C++ to check whether a string starts with a certain string (smaller than the original) ? Just like we can do in Java

C++ 中是否有任何方法可以检查字符串是否以某个字符串开头(小于原始字符串)?就像我们可以在 Java 中做的一样

bigString.startswith(smallString);

回答by Some programmer dude

std::string s("Hello world");

if (s.find("Hello") == 0)
{
    std::cout << "String starts with Hello\n";
}

回答by Alan Stokes

You can do this with string::compare(), which offers various options for comparing all or parts of two strings. This version compares smallStringwith the appropriate size prefix of bigString(and works correctly if bigStringis shorter than smallString):

您可以使用 来执行此操作string::compare(),它提供了用于比较两个字符串的全部或部分的各种选项。此版本smallString与适当的大小前缀进行比较bigString(如果bigString短于,则可以正常工作smallString):

bigString.compare(0, smallString.length(), smallString) == 0

I tend to wrap this up in a free function called startsWith(), since otherwise it can look a bit mysterious.

我倾向于将其封装在一个名为 的免费函数中startsWith(),否则它看起来会有点神秘。

UPDATE: C++20 is addingnew starts_withand ends_withfunctions, so you will finally be able to write just bigString.starts_with(smallString).

更新:C++20 正在添加newstarts_withends_with函数,因此您最终将能够只编写bigString.starts_with(smallString).

回答by Kleist

The approaches using string::find()or string::substr()are not optimal since they either make a copy of your string, or search for more than matches at the beginning of the string. It might not be an issue in your case, but if it is you could use the std::equalalgorithm. Remember to check that the "haystack" is at least as long as the "needle".

使用string::find()or的方法string::substr()不是最佳的,因为它们要么复制您的字符串,要么在字符串的开头搜索多个匹配项。在您的情况下,这可能不是问题,但如果是,您可以使用该std::equal算法。请记住检查“干草堆”是否至少与“针”一样长。

#include <string>    

using namespace std;

bool startsWith(const string& haystack, const string& needle) {
    return needle.length() <= haystack.length() 
        && equal(needle.begin(), needle.end(), haystack.begin());
}

回答by avakar

The correct solution, as always, comes from Boost: boost::algorithm::starts_with.

与往常一样,正确的解决方案来自 Boost: boost::algorithm::starts_with

回答by Borzh

To optimize a little bit:

稍微优化一下:

if ( smallString.size() <= bigString.size() &&
     strncmp( smallString.c_str(), bigString.c_str(), smallString.length() ) == 0 )

Don't forget to #include <cstring>or #include <string.h>

不要忘记#include <cstring>#include <string.h>

回答by Roi Danton

With C++20 you can use std::basic_string::starts_with(or std::basic_string_view::starts_with):

使用 C++20,您可以使用std::basic_string::starts_with(或std::basic_string_view::starts_with):

#include <string_view>

std::string_view bigString_v("Winter is gone"); // std::string_view avoids the copy in substr below.
std::string_view smallString_v("Winter");
if (bigString_v.starts_with(smallString_v))
{
    std::cout << "Westeros" << bigString_v.substr(smallString_v.size());
}

回答by James Kanze

The simplest approach would be:

最简单的方法是:

if ( smallString.size() <= bigString.size()
    && std::equals( smallString.begin(), smallString.end(), bigString.end() )

(This will also work if one of the two, or both, is a vector. Or any other standard container type.)

(如果两者之一或两者都是向量,这也将起作用。或任何其他标准容器类型。)

回答by rogerlsmith

strstr()returns a pointer to the first occurrence of a string within a string.

strstr()返回指向字符串中字符串第一次出现的指针。

回答by cute_ptr

I thought it makes sense to post a raw solution that doesn't use any library functions...

我认为发布一个不使用任何库函数的原始解决方案是有意义的......

// Checks whether `str' starts with `start'
bool startsWith(const std::string& str, const std::string& start) {
    if (&start == &str) return true; // str and start are the same string
    if (start.length() > str.length()) return false;
    for (size_t i = 0; i < start.length(); ++i) {
        if (start[i] != str[i]) return false;
    }
    return true;
}

Adding a simple std::tolowerwe can make this case insensitive

添加一个简单的std::tolower我们可以使这种情况不区分大小写

// Checks whether `str' starts with `start' ignoring case
bool startsWithIgnoreCase(const std::string& str, const std::string& start) {
    if (&start == &str) return true; // str and start are the same string
    if (start.length() > str.length()) return false;
    for (size_t i = 0; i < start.length(); ++i) {
        if (std::tolower(start[i]) != std::tolower(str[i])) return false;
    }
    return true;
}

回答by Samuel Joseph Venable

I'm surprised no one has posted this method yet:

我很惊讶还没有人发布这种方法:

#include <string>    
using namespace std;

bool starts_with(const string& smaller_string, const string& bigger_string) 
{
    return (smaller_string == bigger_string.substr(0,smaller_string.length()));
}