反向查找指向 cstring 中字符第 n 次出现的指针

Reverse Find pointer to nth occurrence of a character in cstring

如何反向查找指向第 n 个字符在 cstring/BSTR 中出现的指针?

char * RFindNthOccurrence(char* src, char t, int n)
{
   //for i/p string src = "HI,There,you,All"
   // and t =','
   // n =2
   //returned pointer should be at ",you,All" in same unchanged string
}

我找到了第一次和最后一次搜索,但没有修改字符串反向查找第 n 次出现是问题。

这个怎么样

// assume n > 0
char * RFindNthOccurrence(char * str, char t, int n) {
    int count = 0;
    char *res = NULL;
    while (str) {
       if (t == *str){
        ++count; 
        if (count >= n) {
            res = str;
       }
       ++str;
    }
    return res;
}

这个怎么样?

#include <iostream>

const char * RFindNthOccurrence( const char *s, char c, size_t n )
{
    if ( !n ) return NULL;

    while ( ( n -= *s == c ) && *s ) ++s;

    return n == 0 ? s : NULL;
}

char * RFindNthOccurrence( char *s, char c, size_t n )
{
    if ( !n ) return NULL;

    while ( ( n -= *s == c ) && *s ) ++s;

    return n == 0 ? s : NULL;
}

int main() 
{
    const char *s1 = "HI,There,you,All";

    std::cout << RFindNthOccurrence( s1, ',', 2 ) << std::endl;

    char s2[] = "HI,There,you,All";

    std::cout << RFindNthOccurrence( s2, ',', 2 ) << std::endl;

    return 0;
}

程序输出为

,you,All
,you,All

该函数的行为与标准 C 函数 strchr 相同,即它找到终止零字符,但仅在 n = 1 的情况下。

另一个例子

#include <iostream>

const char * RFindNthOccurrence( const char *s, char c, size_t n )
{
    if ( !n ) return NULL;

    while ( ( n -= *s == c ) && *s ) ++s;

    return n == 0 ? s : NULL;
}

char * RFindNthOccurrence( char *s, char c, size_t n )
{
    if ( !n ) return NULL;

    while ( ( n -= *s == c ) && *s ) ++s;

    return n == 0 ? s : NULL;
}

int main() 
{
    const char *s = "HI,There,you,All";
    const char *p = s;

    for ( size_t i = 1; p = RFindNthOccurrence( s, ',', i ); ++i )
    {
        std::cout << i << ": " << p << std::endl;
    }

    return 0;
}

程序输出为

1: ,There,you,All
2: ,you,All
3: ,All

与使用标准 C 函数 strchr 相同,无需编写特殊函数。例如

#include <iostream>
#include <cstring>

int main() 
{
    const char *s = "HI,There,you,All";
    const char *p = s;
    size_t n = 2;

    while ( ( p = std::strchr( p, ',' ) ) && --n ) ++p;

    if ( n == 0 ) std::cout << p << std::endl;

    return 0;
}

程序输出为

,you,All

如果您确实需要反向搜索,那么该函数可以像这个演示程序中的那样

#include <iostream>
#include <cstring>

const char * RFindNthOccurrence( const char *s, char c, size_t n )
{
    if ( !n ) return NULL;

    const char *p = s + std::strlen( s );

    while ( ( n -= *p == c ) && p != s ) --p;

    return n == 0 ? p : NULL;
}

int main() 
{
    const char *s = "HI,There,you,All";
    const char *p = s;

    for ( size_t i = 1; p = RFindNthOccurrence( s, ',', i ); ++i )
    {
        std::cout << i << ": " << p << std::endl;
    }

    return 0;
}

在这种情况下,程序输出是

1: ,All
2: ,you,All
3: ,There,you,All