我怎么能计算“_”的数量在一个字符串像“bla_bla_blabla_bla”?
当前回答
你能想到的……Lambda版本……:)
using namespace boost::lambda;
std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;
你需要几个include…我把这个留给你们做练习。
其他回答
计算字符串中出现的字符很简单:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s="Sakib Hossain";
int cou=count(s.begin(),s.end(),'a');
cout<<cou;
}
public static void main(String[] args) {
char[] array = "aabsbdcbdgratsbdbcfdgs".toCharArray();
char[][] countArr = new char[array.length][2];
int lastIndex = 0;
for (char c : array) {
int foundIndex = -1;
for (int i = 0; i < lastIndex; i++) {
if (countArr[i][0] == c) {
foundIndex = i;
break;
}
}
if (foundIndex >= 0) {
int a = countArr[foundIndex][1];
countArr[foundIndex][1] = (char) ++a;
} else {
countArr[lastIndex][0] = c;
countArr[lastIndex][1] = '1';
lastIndex++;
}
}
for (int i = 0; i < lastIndex; i++) {
System.out.println(countArr[i][0] + " " + countArr[i][1]);
}
}
伪代码:
count = 0
For each character c in string s
Check if c equals '_'
If yes, increase count
c++示例代码:
int count_underscores(string s) {
int count = 0;
for (int i = 0; i < s.size(); i++)
if (s[i] == '_') count++;
return count;
}
注意,这是与std::string一起使用的代码,如果你使用char*,将s.s size()替换为strlen(s)。
另外注意:我可以理解你想要“尽可能小”的东西,但我建议你使用这个解决方案。正如你所看到的,你可以使用一个函数来封装代码,这样你就不必每次都写出for循环,但可以在剩下的代码中使用count_下划线("my_string_")。在这里,使用高级c++算法当然是可行的,但我认为这太过了。
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 <algorithm>
std::string s = "a_b_c";
std::string::difference_type n = std::count(s.begin(), s.end(), '_');
推荐文章
- 解析c++中的命令行参数?
- 我如何在c++中创建一个随机的字母数字字符串?
- c++中的atan和atan2有什么区别?
- 如何使用JavaScript大写字符串中每个单词的第一个字母?
- 现代c++能让你免费获得性能吗?
- 一门语言是如何自我扩展的?
- 如何使用cmake创建共享库?
- c++11返回值优化或移动?
- Java中的split()方法对点(.)不起作用。
- Windows和Linux上的c++编译:ifdef开关
- 我如何检查如果一个变量是JavaScript字符串?
- 如何显示有两个小数点后的浮点数?
- 在Lua中拆分字符串?
- c++中size_t和int的区别是什么?
- 在C和c++中静态变量存储在哪里?