程序中的循环似乎至少执行一次,即使子串没有出现也是如此。这是为什么?
#include <iostream>
#include <string>
using namespace std;
int countSubstrings(const string& original_string, const string& substr) {
int number_of_ocurrences = 0;
int i = 0;
for (i = original_string.find(original_string, 0); i != string::npos;
i = original_string.find(substr, i)) {
number_of_ocurrences++;
i++;
}
return number_of_ocurrences;
}
int main() {
string input;
while (1) {
cout << "Enter a a line of text: ";
getline(cin, input, '\n');
cout << '\n';
cout << "Number of ocurrences of the word needle: ";
cout << countSubstrings(input, "needle") << '\n';
}
}
答案 0 :(得分:2)
最初,当你在for循环中设置i
时,你有
original_string.find(original_string, 0)
因此,您正在搜索它将找到的字符串。我相信你的意思是
original_string.find(substr, 0)
答案 1 :(得分:-1)
下面的代码与您的问题没有直接关系,但是,我认为这可能是该概念(通过C ++中的字符串循环)和新手的一个很好的例子。
public static async Task<HttpResponseMessage> Run(HttpRequest req, ILogger log)
{
//string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
MemoryStream ms = new MemoryStream();
await req.Body.CopyToAsync(ms);
byte[] imageBytes = ms.ToArray();
log.LogInformation(imageBytes.Length.ToString());
// ignore below (not related)
string finalString = "Upload succeeded";
Returner returnerObj = new Returner();
returnerObj.returnString = finalString;
var jsonToReturn = JsonConvert.SerializeObject(returnerObj);
return new HttpResponseMessage(HttpStatusCode.OK) {
Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
};
}
public class Returner
{
public string returnString { get; set; }
}
此代码的输出是:
#include <iostream>
using namespace std;
int main (){
string mainString = "foo bar foo bar bar";
string searchedString = "bar";
int numberOfOccurences = 0;
size_t position = mainString.find(searchedString);
while( position != std::string::npos ){
cout<< "There is '" << searchedString << "' at position '" << position <<"' in '"<<mainString <<"'"<<endl;
position += searchedString.length();
position = mainString.find(searchedString, position);
numberOfOccurences++;
}
cout<<"In total, there are "<< numberOfOccurences <<" '"<< searchedString <<"'"<<endl;
return 0;
}
有关更多信息,请访问以下链接。
string.find
第一个匹配项的第一个字符的位置。 如果未找到匹配项,则该函数返回string :: npos。std::string::npos
此值用作字符串成员函数中len(或sublen)参数的值时,表示“直到字符串结尾”。