如何在cstring / BSTR中反向查找指向第n个字符的指针?
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次出现就是问题。
答案 0 :(得分:1)
这个怎么样
// 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;
}
答案 1 :(得分: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 *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