反向查找指针,以n在CSTRING中出现一个字符

Reverse Find pointer to nth occurrence of a character in cstring

本文关键字:字符 一个 CSTRING 指针 查找      更新时间:2023-10-16

如何反向查找指针以在cstring/bstr中出现nthe nth?

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
}

我已经找到了第一次也是最后一次发生搜索,但是不修改字符串反向查找nth的情况是问题。

这个

怎么样
// 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
相关文章: