c 函数 字符串 find_如何在C ++中使用字符串find()

c 函数 字符串 find

In this article, we’ll take a look at how we can use String find() in C++.

在本文中,我们将研究如何在C ++中使用String find()

If we want to check whether a string contains another string, the std::string.find() method is very useful. Let’s understand how we can use this method, with some examples!

如果我们要检查一个字符串是否包含另一个字符串,则std::string.find()方法非常有用。 让我们通过一些示例来了解如何使用此方法!



C ++中String find()的语法 (Syntax of String find() in C++)

This method belongs to the C++ string class (std::string). And therefore, we must include the header file <string>,

此方法属于C ++字符串类( std::string )。 因此,我们必须包括头文件<string>

We must invoke this on a string object, using another string as an argument.

我们必须使用另一个字符串作为参数在一个字符串对象上调用它。

The find() method will then check if the given string lies in our string. It will return the size of the sub-string including the '\0' terminating character (as size_t). But if the string does not lie in our original string, it will return 0.

然后, find()方法将检查给定的字符串是否在我们的字符串中。 它将返回子字符串的大小,包括'\0'终止字符(如size_t )。 但是,如果该字符串不在我们的原始字符串中,它将返回0。

With that, the function is defined like this:

这样,该函数的定义如下:


size_t find(const std::string& my_string, size_t pos = 0);

There is one more parameter, pos, which defines the starting position to search from.

还有一个参数pos ,它定义了要搜索的起始位置。

By default, it is 0, so unless you explicitly specify the start position, searching will happen from the start of the string.

默认情况下为0,因此,除非您明确指定起始位置,否则搜索将从字符串的开头开始。

Also notice that the string is passed by const reference.

还要注意,该字符串是通过const reference传递的。

As we’re not modifying any of the strings, it makes more sense to not waste time creating a temporary string, as we can directly work with references.

由于我们不修改任何字符串,因此更有意义的是不要浪费时间创建临时字符串,因为我们可以直接使用引用。

NOTE: From C++20 onward, many of the standard library methods are now constexpr compatible, so they are executed during compile time itself. You can read more about constexpr intricacies online.

注意 :从C ++ 20开始,许多标准库方法现在都与constexpr兼容,因此它们是在编译时本身执行的。 您可以在线阅读有关constexpr复杂性的更多信息。

There are a couple of function overloads, most of which I will be skipping since you can look at this page for more information. Instead, we’ll focus on one particular overload, that involves the substring length.

有几个函数重载,由于您可以在页面上找到更多信息,因此我将跳过其中的大多数。 相反,我们将重点放在一种特定的重载上,该重载涉及子字符串的长度。


size_t find( const Char* s, size_type pos, size_type count )

This particular overload checks if the substring lies within our string, but it also has a limit for the substring length. This will match until count characters.

这种特殊的重载检查子字符串是否位于我们的字符串内,但它也对子字符串长度有限制。 匹配直到count字符。

But this cannot be used for std::string. Notice that const Char* in the prototype. So, we can use this only for C-style strings.

但这不能用于std::string 。 注意原型中的const Char* 。 因此,我们只能将其用于C样式的字符串。

For example, if we pass the substring “Hell” to “Hello” to this function.

例如,如果我们将子字符串“ Hell”传递给“ Hello”,则该函数被传递。


std::cout << "Hello".find("Hell", 0, 3) << std::endl;

This will only match 3 characters, from the start of “Hello”. So, we’ll get only 4 bytes as the output, as opposed to 5.

从“ Hello”开始,只能匹配3个字符。 因此,我们将仅获得4个字节作为输出,而不是5个字节。

Let’s now look at some examples to understand what we’ve learnt.

现在让我们看一些例子来了解我们所学到的东西。



在C ++中使用string.find() (Using string.find() in C++)

Let’s look at the default call, when pos=0. We’ll simply search for the whole substring, from the start of the string.

让我们看一下默认调用,即pos=0 。 我们将从字符串的开头简单地搜索整个子字符串。


#include <iostream>
#include <string>

int main() {
    // Create our string
    std::string my_str("Hello from JournalDev");
    // Target string to search for
    std::string target_string("JournalDev");

    std::cout << "Is " << target_string << " a substring of " << my_str << " ?\n";
    size_t substring_length = my_str.find(target_string);
    if (substring_length == 0)
        std::cout << "No\n";
    else
        std::cout << "Length of matched substring = " << substring_length << std::endl;

    return 0;
}

Output:

输出


Is JournalDev a substring of Hello from JournalDev ?
Length of matched substring = 11

As you can see, the substring is indeed there inside our original string!

如您所见,子字符串确实存在于原始字符串中!

Let’s now search the same substring from a specific position on the string.

现在让我们从字符串上的特定位置搜索相同的子字符串。


#include <iostream>
#include <string>

int main() {
    // Create our string
    std::string my_str("Hello from JournalDev");
    // Target string to search for
    std::string target_string("JournalDev");

    std::cout << "Is " << target_string << " a substring of " << my_str << " ?\n";
    size_t substring_length = my_str.find(target_string, 12); // Start from index 12 (from my_str[12])
    if (substring_length == 0)
        std::cout << "No\n";
    else
        std::cout << "Length of matched substring = " << substring_length << std::endl;

    return 0;
}

Output

输出量


Is JournalDev a substring of Hello from JournalDev ?
Length of matched substring = 18446744073709551615

Why are we getting such a weird output? Well, since we started from index 12 on the original string, and the length of our sub-string, from this position, will go beyond the length of the original string!

为什么我们得到如此奇怪的输出? 好吧,由于我们从原始字符串的索引12开始,因此从该位置开始,子字符串的长度将超出原始字符串的长度!

We therefore go to a garbage location, after reaching the end of our string. find() goes beyond the end of the string, so keep this in mind.

因此,在到达字符串的末尾之后,我们进入了垃圾回收位置。 find()超出了字符串的末尾,因此请记住这一点。

We’ll therefore fix this dangerous state, by checking whether we’ve reached the end of the string.

因此,我们将通过检查是否到达字符串的末尾来修复此危险状态。

C++ has a special variable called std::string::npos, that returns a handle to the current string that we can use to detect if we’ve reached the end of our string.

C ++有一个称为std::string::npos的特殊变量,该变量返回当前字符串的句柄,我们可以使用该句柄来检测是否已到达字符串的末尾。


if (my_str.find(target_str) != std::string::npos) {
    // This matches! We're still within the original string
}
else {
    // Oops! Out of bounds. Print error message!
}

With this change, our code will now look like this:

进行此更改后,我们的代码现在将如下所示:


#include <iostream>
#include <string>

int main() {
    // Create our string
    std::string my_str("Hello from JournalDev");
    // Target string to search for
    std::string target_string("JournalDev");

    std::cout << "Is " << target_string << " a substring of " << my_str << " ?\n";
    size_t substring_length;
    if ((substring_length = my_str.find(target_string, 12)) != std::string::npos) {
        std::cout << "Length of matched substring = " << substring_length << std::endl;
    }
    else {
        std::cout << "No\n";
    }

    return 0;
}

Output

输出量


Is JournalDev a substring of Hello from JournalDev ?
No

Now, we get our expected output, since we start from index 12!

现在,我们从索引12开始,获得了预期的输出!

Let’s use this check to show the other overloaded form of find(), using a count. Remember that we cannot use this form directly on C++ strings.

让我们使用此检查通过count来显示find()的其他重载形式。 请记住,我们不能直接在C ++字符串上使用这种形式。


#include <iostream>
#include <string>

int main() {
    // Create our string
    std::string my_str("Hello from JournalDev");
    // Target string to search for
    std::string target_string("Journ_kkfffsfsfskkk");

    std::cout << "Is " << target_string << " a substring of " << my_str << " ?\n";
    size_t substring_length;
    // Use a count to match only 5 characters
    // Note that we can use this form only for const char* strings
    if ((substring_length = my_str.find("Journ_kkfffsfsfskkk", 0, 5)) != std::string::npos) {
        std::cout << "Length of matched substring = " << substring_length << std::endl;
    }
    else {
        std::cout << "No\n";
    }

    return 0;
}

Output

输出量


Is Journ_kkfffsfsfskkk a substring of Hello from JournalDev ?
Length of matched substring = 11

Observe that our we’ve changed our target string. Here, although only the first 5 characters will get matched, that is enough for find(), since we’ve put a counter limit of 5!

观察我们已经更改了目标字符串。 在这里,尽管只有前5个字符会被匹配,但对于find()来说已经足够了,因为我们将计数器限制为5!

So, it will simply ignore the rest of the target sub-string, and continue matching our original string until the end of the string!

因此,它将仅忽略目标子字符串的其余部分,并继续匹配我们的原始字符串,直到字符串结尾!

That’s why we still get 11, since that’s where the substring match is found.

这就是为什么我们仍然得到11的原因,因为这是找到子字符串匹配的地方。



结论 (Conclusion)

Hopefully, with all these example, you’ve understood how you can easily start using the string.find() method in C++. If you have any doubts, do ask them in the comment section below!

希望通过所有这些示例,您已经了解了如何轻松地开始使用字符串。 C ++中的find()方法。 如果您有任何疑问,请在下面的评论部分中提问!

Also, do have a look at some of our other articles related to C++ in our tutorials section!

另外,请在我们的教程部分中查看其他一些与C ++相关的文章!



参考资料 (References)



翻译自: https://www.journaldev.com/37832/string-find-c-plus-plus

c 函数 字符串 find

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值