我怎么能计算“_”的数量在一个字符串像“bla_bla_blabla_bla”?
当前回答
具有适当命名变量的老式解决方案。这给了代码一些精神。
#include <cstdio>
int _(char*__){int ___=0;while(*__)___='_'==*__++?___+1:___;return ___;}int main(){char*__="_la_blba_bla__bla___";printf("The string \"%s\" contains %d _ characters\n",__,_(__));}
编辑:大约8年后,看到这个答案,我为自己这么做感到羞愧(尽管我对自己说,这是对一个不费力气的问题的讽刺)。这是有害的,是不好的。我不是要移除这根柱子;我添加这个道歉是为了帮助改变StackOverflow上的气氛。所以OP:我道歉,我希望你的作业是正确的,尽管我的喷子,像我这样的答案并没有阻止你参与网站。
其他回答
#include <algorithm>
std::string s = "a_b_c";
std::string::difference_type n = std::count(s.begin(), s.end(), '_');
std::string有几个用于搜索的方法,但find可能是你要找的。如果您指的是c风格的字符串,那么等效的是strchr。然而,在这两种情况下,您也可以使用for循环并检查每个字符—循环本质上是这两个字符的结义。
一旦你知道如何找到给定起始位置的下一个字符,你就可以不断地推进搜索(即使用循环),一边计算一边计算。
Try
#include <iostream>
#include <string>
using namespace std;
int WordOccurrenceCount( std::string const & str, std::string const & word )
{
int count(0);
std::string::size_type word_pos( 0 );
while ( word_pos!=std::string::npos )
{
word_pos = str.find(word, word_pos );
if ( word_pos != std::string::npos )
{
++count;
// start next search after this word
word_pos += word.length();
}
}
return count;
}
int main()
{
string sting1="theeee peeeearl is in theeee riveeeer";
string word1="e";
cout<<word1<<" occurs "<<WordOccurrenceCount(sting1,word1)<<" times in ["<<sting1 <<"] \n\n";
return 0;
}
我会这样做:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int count = 0;
string s("Hello_world");
for (int i = 0; i < s.size(); i++)
{
if (s.at(i) == '_')
count++;
}
cout << endl << count;
cin.ignore();
return 0;
}
你能想到的……Lambda版本……:)
using namespace boost::lambda;
std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;
你需要几个include…我把这个留给你们做练习。
推荐文章
- 解析c++中的命令行参数?
- 我如何在c++中创建一个随机的字母数字字符串?
- c++中的atan和atan2有什么区别?
- 如何使用JavaScript大写字符串中每个单词的第一个字母?
- 现代c++能让你免费获得性能吗?
- 一门语言是如何自我扩展的?
- 如何使用cmake创建共享库?
- c++11返回值优化或移动?
- Java中的split()方法对点(.)不起作用。
- Windows和Linux上的c++编译:ifdef开关
- 我如何检查如果一个变量是JavaScript字符串?
- 如何显示有两个小数点后的浮点数?
- 在Lua中拆分字符串?
- c++中size_t和int的区别是什么?
- 在C和c++中静态变量存储在哪里?