[英]CPP: How to get last index of a char?
I have this word occurrences example: 我有这个单词出现的例子:
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;
}
So in my main function: 所以在我的主要功能中:
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;
It doesn't works because i need to add an ' ' blank character at the final of str1 as below: 它不起作用,因为我需要在str1的末尾添加一个''空白字符,如下所示:
char str1[] = "Hi today is monday yeah ";
char str2[] = "yeah ";
How can i compare if the last index is 'null' in my while loop to make it work? 我如何比较while循环中的最后一个索引是否为“ null”以使其工作? I tried adding the sentence in the OR operator: while(nn[i] == ' ' || nn[i] == '\\0')
as can you see, but it not works. 我尝试在OR运算符中添加该句子:如您所见, while(nn[i] == ' ' || nn[i] == '\\0')
,但它不起作用。
#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;
}
You have it written as: 您将其写为:
if(nn[i] == ' ' || n[i] == '\0')
That has a single n
character in it. 那里面有一个n
字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.