计算字符串中出现的字符数

时间:2022-01-01 04:16:30

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

如何计算字符串中“_”的数量,比如“bla_bla_blabla_bla”?

11 个解决方案

#1


310  

#include <algorithm>

std::string s = "a_b_c";
size_t n = std::count(s.begin(), s.end(), '_');

#2


27  

Pseudocode:

伪代码:

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

EDIT: C++ example code:

编辑:c++示例代码:

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).

注意,这是与std一起使用的代码::string,如果您使用char*,则用strlen(s)替换。size()。

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.

注意:我可以理解你想要“尽可能小”的东西,但是我建议你用这个解决方案。正如您所看到的,您可以使用一个函数为您封装代码,这样您就不必每次都写for循环,而只需在代码的其余部分使用count_下划线(“my_string_”)。在这里使用高级c++算法当然是可能的,但我认为这有点过头了。

#3


17  

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",__,_(__));}

#4


10  

#include <boost/range/algorithm/count.hpp>

std::string str = "a_b_c";
int cnt = boost::count(str, '_');

#5


7  

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

你的名字…Lambda版本……:)

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...

你需要几个包括……我把它留给你们作为练习……

#6


4  

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.

std::string for search有几种方法,但是find可能是您要查找的。如果你指的是c风格的字符串,那么等价的是strchr。然而,在任何一种情况下,您都可以使用for循环并检查每个字符——循环本质上就是这两个循环。

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.

一旦你知道如何在给定的起始位置找到下一个字符,你就会不断地推进你的搜索(例如使用一个循环),边走边计算。

#7


3  

Count character occurrences in a string is easy:

计算字符串中出现的字符数很容易:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s="Sakib Hossain";
    int cou=count(s.begin(),s.end(),'a');
    cout<<cou;
}

#8


2  

You can find out occurrence of '_' in source string by using string functions. find() function takes 2 arguments , first - string whose occurrences we want to find out and second argument takes starting position.While loop is use to find out occurrence till the end of source string.

通过使用字符串函数,可以发现源字符串中出现的'_'。find()函数接受两个参数,第一个字符串,我们想要查找它的出现,第二个参数位于起始位置。While循环用于查找事件的发生,直到源字符串的结束。

example:

例子:

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();
} 

#9


1  

I would have done this way :

我会这样做:

#include <iostream>
#include <string>
using namespace std;
int main()
{

int count = 0;
string s("Hello_world");

for (int i = 0; i < s.size(); i++) //can't be i <= s.size() because s.at(s.size()) will result in overflow
        { if (s.at(i) == '_')    count++;
}
    cout << endl << count;
    cin.ignore();
    return 0;
    }

#10


-2  

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]);
        }
    }

#11


-3  

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;
}

#1


310  

#include <algorithm>

std::string s = "a_b_c";
size_t n = std::count(s.begin(), s.end(), '_');

#2


27  

Pseudocode:

伪代码:

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

EDIT: C++ example code:

编辑:c++示例代码:

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).

注意,这是与std一起使用的代码::string,如果您使用char*,则用strlen(s)替换。size()。

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.

注意:我可以理解你想要“尽可能小”的东西,但是我建议你用这个解决方案。正如您所看到的,您可以使用一个函数为您封装代码,这样您就不必每次都写for循环,而只需在代码的其余部分使用count_下划线(“my_string_”)。在这里使用高级c++算法当然是可能的,但我认为这有点过头了。

#3


17  

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",__,_(__));}

#4


10  

#include <boost/range/algorithm/count.hpp>

std::string str = "a_b_c";
int cnt = boost::count(str, '_');

#5


7  

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

你的名字…Lambda版本……:)

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...

你需要几个包括……我把它留给你们作为练习……

#6


4  

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.

std::string for search有几种方法,但是find可能是您要查找的。如果你指的是c风格的字符串,那么等价的是strchr。然而,在任何一种情况下,您都可以使用for循环并检查每个字符——循环本质上就是这两个循环。

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.

一旦你知道如何在给定的起始位置找到下一个字符,你就会不断地推进你的搜索(例如使用一个循环),边走边计算。

#7


3  

Count character occurrences in a string is easy:

计算字符串中出现的字符数很容易:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s="Sakib Hossain";
    int cou=count(s.begin(),s.end(),'a');
    cout<<cou;
}

#8


2  

You can find out occurrence of '_' in source string by using string functions. find() function takes 2 arguments , first - string whose occurrences we want to find out and second argument takes starting position.While loop is use to find out occurrence till the end of source string.

通过使用字符串函数,可以发现源字符串中出现的'_'。find()函数接受两个参数,第一个字符串,我们想要查找它的出现,第二个参数位于起始位置。While循环用于查找事件的发生,直到源字符串的结束。

example:

例子:

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();
} 

#9


1  

I would have done this way :

我会这样做:

#include <iostream>
#include <string>
using namespace std;
int main()
{

int count = 0;
string s("Hello_world");

for (int i = 0; i < s.size(); i++) //can't be i <= s.size() because s.at(s.size()) will result in overflow
        { if (s.at(i) == '_')    count++;
}
    cout << endl << count;
    cin.ignore();
    return 0;
    }

#10


-2  

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]);
        }
    }

#11


-3  

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;
}