我怎么能计算“_”的数量在一个字符串像“bla_bla_blabla_bla”?
当前回答
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]);
}
}
其他回答
#include <boost/range/algorithm/count.hpp>
std::string str = "a_b_c";
int cnt = boost::count(str, '_');
具有适当命名变量的老式解决方案。这给了代码一些精神。
#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:我道歉,我希望你的作业是正确的,尽管我的喷子,像我这样的答案并没有阻止你参与网站。
使用lambda函数检查字符是否为“_”,则唯一的计数将增加,否则不是有效字符
std::string s = "a_b_c";
size_t count = std::count_if( s.begin(), s.end(), []( char c ){return c =='_';});
std::cout << "The count of numbers: " << count << std::endl;
你能想到的……Lambda版本……:)
using namespace boost::lambda;
std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;
你需要几个include…我把这个留给你们做练习。
std::string有几个用于搜索的方法,但find可能是你要找的。如果您指的是c风格的字符串,那么等效的是strchr。然而,在这两种情况下,您也可以使用for循环并检查每个字符—循环本质上是这两个字符的结义。
一旦你知道如何找到给定起始位置的下一个字符,你就可以不断地推进搜索(即使用循环),一边计算一边计算。