這個怎麼樣?
#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
你必須找到第一個出現的代碼是什麼?你只需要添加一個計數器繼續下去,直到你看到第n次出現爲止。 – NathanOliver
查找字符串的結尾並在計數時返回。 – dasblinkenlight
您是否試圖從第一個或第n個結果中反向查找第n個出現? –