字符串的第 n 次出现的索引

Index of nth Occurrence of the string

本文关键字:索引 字符串      更新时间:2023-10-16

如何在一行中找到给定字符串的第n次出现的索引?我需要它从该索引中获取一个子字符串。这可以通过 c++ 中的任何函数实现吗?

Boost:

中有一个find_nth模板函数:http://www.boost.org/doc/libs/1_54_0/doc/html/boost/algorithm/find_nth.html

#include <iostream>
#include <boost/algorithm/string/find.hpp>
using namespace std;
using namespace boost;
int main() {
    string a = "The rain in Spain falls mainly on the plain";
    iterator_range<string::iterator> r = find_nth(a, "ain", 2);
    cout << std::distance(a.begin(), r.begin()) << endl;
    return 0;
}
为此

,您可以使用std::string::find并跟踪返回的位置。执行此操作时,您可以检查是否也找不到所需的字符串并返回 -1。

#include <string>
int nthOccurrence(const std::string& str, const std::string& findMe, int nth)
{
    size_t  pos = 0;
    int     cnt = 0;
    while( cnt != nth )
    {
        pos+=1;
        pos = str.find(findMe, pos);
        if ( pos == std::string::npos )
            return -1;
        cnt++;
    }
    return pos;
}

您可以使用以下函数

#include <string.h>
int strpos(char *haystack, char *needle, int nth)
{
    char *res = haystack;
    for(int i = 1; i <= nth; i++)
    {
        res = strstr(res, needle);
        if (!res)
            return -1;
        else if(i != nth)
            res++;
    }
    return res - haystack;
}

如果找不到第 n 个匹配项,则返回 -1。

一种简单的方法,只需使用 std::string::find

size_t find_nth(const string& haystack, size_t pos, const string& needle, size_t nth) 
{
    size_t found_pos = haystack.find(needle, pos);
    if(0 == nth || string::npos == found_pos)  return found_pos;
    return find_nth(haystack, found_pos+1, needle, nth-1);
}

这个模板函数应该可以完成工作

template<typename Iter>
Iter nth_occurence(Iter first, Iter last,
                   Iter first_, Iter last_,
                   unsigned nth)
{
  Iter it = std::search(first, last, first_, last_);
  if (nth == 0) return it;
  if (it == last) return it;
  return nth_occurence(it + std::distance(first_, last_), last,
                       first_, last_, nth -1);
}

用法

int main()
{
  std::string a = "hello world world world end";
  std::string b = "world";
  auto it1 = nth_occurence(begin(a), end(a), begin(b), end(b), 0);
  auto it2 = nth_occurence(begin(a), end(a), begin(b), end(b), 1);
  auto it3 = nth_occurence(begin(a), end(a), begin(b), end(b), 2);
  auto it4 = nth_occurence(begin(a), end(a), begin(b), end(b), 3);
  std::cout << std::distance(begin(a), it1) << "n";
  std::cout << std::distance(begin(a), it2) << "n";
  std::cout << std::distance(begin(a), it3) << "n";
  std::cout << std::boolalpha << (it4 == end(a)) << "n";
}
=> 6, 12, 18, true

另一种方法是使用std::stringfind_first_of/find_last_of中的最后一个参数。对于last-nth搜索,可以通过以下方式执行此操作:

auto find_last_nth(const std::string& haystack, const std::string& needle, size_t n = 1)
{
    assert(0 != n);
    auto found_last = haystack.length();
    while (true)
    {
        found_last = haystack.find_last_of(needle, found_last - 1);
        if (0 == --n || std::string::npos == found_last)
        {
            return found_last;
        }
    }
}

我真的很喜欢 rcs 的答案,它巧妙地使用了指针。我认为,除了使用提升库之外,这是实现 OP 想要的结果的最干净的方式。但是,我在某些不使用指针的代码中实现它时遇到了麻烦(我自己仍然是初学者),所以这里有一个不使用指针或提升库的等效答案。

int strpos(string haystack, char needle, int nth)
{// Will return position of n-th occurence of a char in a string.
        string read;    // A string that will contain the read part of the haystack
        for (int i=1 ; i<nth+1 ; ++i)
        {
                std::size_t found = haystack.find(needle);
                read += haystack.substr(0,found+1); // the read part of the haystack is stocked in the read string
                haystack.erase(0, found+1);     // remove the read part of the haystack up to the i-th needle
                if (i == nth)
                {
                        return read.size();
                }
        }
        return -1;
}