在C++中查找字符串的多种方法

分类:知识百科 日期: 点击:0

C++中查找字符串的多种方法

C++中查找字符串的多种方法包括:
  • 使用标准库函数
  • 使用自定义函数
  • 使用正则表达式

使用标准库函数查找字符串

C++标准库提供了一系列函数来查找字符串,其中包括:

  • find():在字符串中查找指定的子字符串,并返回其位置;
  • find_first_of():在字符串中查找指定字符,并返回其位置;
  • find_first_not_of():在字符串中查找不包含指定字符的字符,并返回其位置;
  • find_last_of():在字符串中查找一个指定字符,并返回其位置;
  • find_last_not_of():在字符串中查找一个不包含指定字符的字符,并返回其位置。
#include 
#include 
 
int main()
{
    std::string str = "Hello World!";
    std::string str2 = "World";
 
    // 查找子字符串
    std::size_t found = str.find(str2);
    if (found!=std::string::npos)
        std::cout << "第一次出现的位置:" << found << '\n';
 
    return 0;
}

使用自定义函数查找字符串

除了使用标准库函数外,我们也可以自定义函数来查找字符串。

  • 暴力法:逐个比较字符串中的每个字符,直到找到符合条件的字符串。
  • KMP算法:KMP算法是一种比较高效的字符串匹配算法,它可以在比较时跳过一些字符,从而提高查找效率。
#include 
#include 
 
// 暴力法查找字符串
int brute_force_search(std::string source, std::string target)
{
    int i = 0;
    int j = 0;
    while (i < source.length() && j < target.length())
    {
        if (source[i] == target[j])
        {
            i++;
            j++;
        }
        else
        {
            i = i - j + 1;
            j = 0;
        }
    }
    if (j == target.length())
        return i - j;
    else
        return -1;
}
 
int main()
{
    std::string str = "Hello World!";
    std::string str2 = "World";
 
    // 查找子字符串
    int found = brute_force_search(str, str2);
    if (found != -1)
        std::cout << "第一次出现的位置:" << found << '\n';
 
    return 0;
}

使用正则表达式查找字符串

正则表达式是一种模式匹配的工具,它可以用来查找字符串中符合某种模式的子字符串。

C++中可以使用正则表达式库来实现正则表达式,其中包括:

  • boost::regex:boost正则表达式库;
  • std::regex:C++11标准正则表达式库;
  • pcre:Perl Compatible Regular Expressions库;
  • POSIX:POSIX兼容的正则表达式库。
#include 
#include 
#include 
 
int main()
{
    std::string str = "Hello World!";
    std::string str2 = "World";
 
    // 使用boost正则表达式库查找子字符串
    boost::regex expr(str2);
    boost::smatch match;
    if (boost::regex_search(str, match, expr))
        std::cout << "第一次出现的位置:" << match.position() << '\n';
 
    return 0;
}

C++中查找字符串的多种方法包括使用标准库函数、使用自定义函数以及使用正则表达式,根据实际情况选择合适的方法即可。

标签:

版权声明

1. 本站所有素材,仅限学习交流,仅展示部分内容,如需查看完整内容,请下载原文件。
2. 会员在本站下载的所有素材,只拥有使用权,著作权归原作者所有。
3. 所有素材,未经合法授权,请勿用于商业用途,会员不得以任何形式发布、传播、复制、转售该素材,否则一律封号处理。
4. 如果素材损害你的权益请联系客服QQ:77594475 处理。