どの"_"ように文字列内の数を数えることができ"bla_bla_blabla_bla"ますか?
どの"_"ように文字列内の数を数えることができ"bla_bla_blabla_bla"ますか?
回答:
#include <algorithm>
std::string s = "a_b_c";
size_t n = std::count(s.begin(), s.end(), '_');std::countタイプが返されますiterator_traits<InputIt>::difference_typeが、ほとんどの標準的なコンテナではそうではstd::ptrdiff_tありませんstd::size_t。
                    疑似コード:
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.size()てくださいstrlen(s)。
また、「できるだけ小さいもの」が必要であることは理解できますが、代わりにこのソリューションを使用することをお勧めします。ご覧のとおり、関数を使用してコードをカプセル化できるため、for毎回ループを記述する必要はありませんがcount_underscores("my_string_")、残りのコードで使用できます。ここでは高度なC ++アルゴリズムを使用することは確かに可能ですが、それはやり過ぎだと思います。
適切に名前が付けられた変数を持つ昔ながらのソリューション。これはコードに精神を与えます。
#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年後、この回答を見て私はこれを行ったことを恥ずかしく思います(たとえ私が低努力の質問で卑劣な口先としてそれを正当化したとしても)。これは有毒であり、OKではありません。私は投稿を削除していません。StackOverflowの雰囲気を変えるのを助けるためにこの謝罪を追加します。OP:申し訳ありません。私のトローリングにもかかわらず、宿題が正しく行われたことを願っています。私のような回答で、サイトへの参加を妨げることはありませんでした。
#include <boost/range/algorithm/count.hpp>
std::string str = "a_b_c";
int cnt = boost::count(str, '_');名前を付けます... Lambdaバージョン... :)
using namespace boost::lambda;
std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;あなたはいくつかのインクルードが必要です...私はあなたにそれを演習として残します...
ラムダ関数を使用して文字が「_」であることを確認すると、カウントのみがインクリメントされ、それ以外の場合は有効な文字ではありません
std::string s = "a_b_c";
size_t count = std::count_if( s.begin(), s.end(), []( char c ){if(c =='_') return true; });
std::cout << "The count of numbers: " << count << std::endl;[]( char c ){if(c =='_') return true; }すべてのコードパスで値を返さなかったため、未定義の動作を呼び出します
                    検索にはstd :: stringのメソッドがいくつかありますが、おそらくfindが探しているものです。Cスタイルの文字列を意味する場合、同等のものはstrchrです。ただし、どちらの場合でも、forループを使用して各文字を確認することもできます。基本的に、ループはこれら2つをまとめたものです。
開始位置を指定して次の文字を見つける方法がわかったら、続けて検索を進めます(つまり、ループを使用します)。
文字列内の文字の出現を数えるのは簡単です:
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s="Sakib Hossain";
    int cou=count(s.begin(),s.end(),'a');
    cout<<cou;
}文字列関数を使用して、ソース文字列内の '_'の出現を確認できます。find()関数は2つの引数を受け取ります。最初の文字列は、その出現を調べたい文字列で、2番目の引数は開始位置をとります。Whileループは、ソース文字列の終わりまでの出現を見つけるために使用されます。
例:
string str2 = "_";
string strData = "bla_bla_blabla_bla_";
size_t pos = 0,pos2;
while ((pos = strData.find(str2, pos)) < strData.length()) 
{
    printf("\n%d", pos);
    pos += str2.length();
} 私はこのようにしたでしょう:
#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;
}私はそのようなことをしたでしょう:)
const char* str = "bla_bla_blabla_bla";
char* p = str;    
unsigned int count = 0;
while (*p != '\0')
    if (*p++ == '_')
        count++;試す
#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;
}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]);
        }
    }