CPP:如何获取字符的最后一个索引?

时间:2018-07-25 01:25:22

标签: c++

我有这个单词出现的例子:

size_t count_occurrences(const char* s, const char* f){
    size_t t1 = strlen(s);
    size_t i = 0;
    size_t j = 0;
    size_t k = 0;
    size_t res = 0;
    auto nn = new char[t1+1];
    memcpy(nn,s,t1+1);
    char tok[200];
    while(i < t1){
        if(nn[i] == ' ' || nn[i] == '\0'){
            while(j < i){
                tok[k] = nn[j];
                k++;
                j++;
            }
            tok[k] = '\0';
            k = 0;
            j = i+1;
            if(strcmp(tok,f) == 0) res++;
            *tok = 0;
        }
        i++;
    }
    return res;
}

所以在我的主要功能中:

char str1[] = "Hi today is monday yeah";
char str2[] = "yeah";
size_t cont = count_occurrences(str1, str2);
cout << "The word: " << str2 << " repeats: " << cont << " times." << endl;

它不起作用,因为我需要在str1的末尾添加一个''空白字符,如下所示:

char str1[] = "Hi today is monday yeah ";
char str2[] = "yeah ";

我如何比较我的while循环中的最后一个索引是否为'null'以使其起作用?如您所见,我尝试在OR运算符中添加以下句子:while(nn[i] == ' ' || nn[i] == '\0'),但它不起作用。

2 个答案:

答案 0 :(得分:-1)

#include <string>
#include <cctype>

size_t count_occurrences(std::string const & haystack, std::string const & needle)
{
    std::size_t count{};
    std::size_t offset{};
    auto const needle_len{ needle.length() };
    auto const hs_len{ haystack.length() };

    if (!(needle_len && hs_len))
        return 0;

    while ((offset = haystack.find(needle, offset)) != std::string::npos) {
        if (hs_len == needle_len)
            return 1;
        if ((!offset && (std::isspace(haystack[needle_len]) || std::ispunct(haystack[needle_len])) ) ||
            ( offset + needle_len == hs_len ) ||
            ( offset && std::isspace(haystack[offset - 1]) &&
            ( std::isspace(haystack[offset + needle_len]) || std::ispunct(haystack[offset + needle_len])) ) )
            ++count;
        offset += needle.length();
    }
    return count;
}

答案 1 :(得分:-4)

您将其写为:

if(nn[i] == ' ' || n[i] == '\0')

其中只有一个n字符。