tags:

views:

235

answers:

6

How can I count the number of "_" in a string like "bla_bla_blabla_bla"?

+11  A: 

Pseudocode:

count = 0
For each character c in string s
  Check if c equals '_'
    If yes, increase count

EDIT: C++ example code:

int count_underscores(string s) {
  int count = 0;

  for (int i = 0; i < s.size(); i++)
    if (s[i] == '_') count++;

  return count;
}

Note that this is code to use together with std::string, if you're using char*, replace s.size() with strlen(s).

Also note: I can understand you want something "as small as possible", but I'd suggest you to use this solution instead. As you see you can use a function to encapsulate the code for you so you won't have to write out the for loop everytime, but can just use count_underscores("my_string_") in the rest of your code. Using advanced C++ algorithms is certainly possible here, but I think it's overkill.

schnaader
Surely we can come up with a totally unreadable templated version with lamba functions and a bind2nd() call ?
Martin Beckett
Of course, and a brainfuck version so he doesn't have to convert pseudocode.
schnaader
@Martin I was actually thinking of that. Unfortunately my grasp of C++ functional programming is practically non-existent.
jdmichal
I think calling a web service would be much more fun than lambdas, then the core algorithm isn't just inscrutable, it's stored elsewhere.
Ben Voigt
This is no homework question. I am new to c++ and don't have enough knowledge of c++ to program this in a advanced manner. Read: as small as possible. I am able to program this in a simple manner with a for loop and so on, but I was looking for an sophisticated solution, something like the solution of Diego. Next time I will give more information for the reason of the question.
andre de boer
+3  A: 

You name it... Lambda version... :)

using namespace boost::lambda;

std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;

You need several includes... I leave you that as an exercise...

Diego Sevilla
Do you really think a newbie is going to understand any of this?
Josh Stodola
@Josh: It appears to be a spinoff of the childish laughter in some [comments](http://stackoverflow.com/questions/3867890/count-character-occurrences-in-a-string/3867921#3867921).
Roger Pate
Some of the world's top programmers have spent the last 15years evolving C++ to the point where we can write this - it's not childish!
Martin Beckett
Making a point that those who do not know Perl are forced to reinvent it (badly) - now that would be childish!
Martin Beckett
Oh, come on, this can also be fun! :) @Roger: Yes, it was kind of an answer to a fun comment by Martin Beckett above. @Martin: Well, yes, it is not particularly appealing, but in the expression you can see clearly _1 is refering to the first parameter to the "lambda", and that it is being compared using "==" to the character... C++0x lambda are not much better in shape, but at least they are standard :)
Diego Sevilla
@Martin: Using lambda isn't childish, but purposefully answering with "totally unreadable templated version", which you suggested, plus the later brainfuck and web services comments, is.
Roger Pate
@Diego: I like your answer (and wasn't calling it childish, but the comments), though I think you have much too little explanation for it to be a good answer to this question. I was just trying to show the context to Josh.
Roger Pate
@Diego, I guessed that (in a Perl kind of way) but in c shouldn't the first parameter be _0 ?
Martin Beckett
+4  A: 

Old-fashioned solution with appropriately named variables. This gives the code some spirit.

#include <cstdio>
int _(char*__){int ___=0;while(*__)___='_'==*__++?___+1:___;return ___;}int main(){char*__="_la_blba_bla__bla___";printf("The string \"%s\" contains %d _ characters\n",__,_(__));}
Tamás Szelei
why not `c+='_'==*str;`?
Ben Voigt
Also, doesn't test the first character. Switch to do-while to fix.
Ben Voigt
While that might work in practice, `true` does not equal 1, but an arbitrary value which is not 0.
Tamás Szelei
Seriously? A purposefully obfuscated answer is the best you can do and you think it would ever be appropriate here?
Roger Pate
@Tamas: int(true) is always 1 in C++.
Roger Pate
@Roger: Are you always taking yourself so seriously?
Tamás Szelei
a truly old fashioned solution would declare a prototype for sprintf instead of #including a *whole header file*!
John Dibling
@Tamas: Of course not, but I don't have my fun while "answering" beginners' questions.
Roger Pate
Love it. Shame it violates the double underscore rule.
Martin York
You could replace some _ with $ signs (not sure if it is legal but it works with gcc)
Martin York
@Martin: That's a gcc extension.
Roger Pate
A: 

How about using the new regex_ in C++0x for extra credits :)?

Atul
Counting in regex is kinda ugly, but one process is along the lines of strip out what you don't want to count `/[^_]//` and then count by reduction `/__________/x/` tens, `/xxxxxxxxxx/V/` hundreds and convert to a number `/__/2` `/_/1`
Greg Domjan
+2  A: 

There are several methods of std::string for searching, but find is probably what you're looking for. If you mean a C-style string, then the equivalent is strchr. However, in either case, you can also use a for loop and check each character—the loop is essentially what these two wrap up.

Once you know how to find the next character given a starting position, you continually advance your search (i.e. use a loop), counting as you go.

Roger Pate
A: 

Hello.

#include <algorithm>
std::string s = "a_b_c";
int i = std::count(s.begin(), s.end(), '_');
Benoit