C ++에서 문자열의 문자 발생 수 계산
"_"
문자열 의 수를 어떻게 계산
"bla_bla_blabla_bla"
합니까?
#include <algorithm>
std::string s = "a_b_c";
size_t n = std::count(s.begin(), s.end(), '_');
의사 코드 :
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 version ... :)
using namespace boost::lambda;
std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;
당신은 몇 가지 포함이 필요합니다 ... 나는 당신을 운동으로 남겨두고 ...
검색을위한 std :: string에는 여러 가지 방법이 있지만 find는 아마도 당신이 찾고있는 것입니다. C 스타일 문자열을 의미하는 경우 strchr입니다. 그러나 두 경우 모두 for 루프를 사용하여 각 문자를 확인할 수 있습니다. 루프는 본질적으로이 두 가지를 마무리합니다.시작 위치가 주어진 다음 문자를 찾는 방법을 알고 나면 계속 탐색하면서 루프를 사용하여 검색을 진행합니다.
문자열 함수를 사용하여 소스 문자열에서 '_'의 발생을 찾을 수 있습니다. find () 함수는 2 개의 인수를 취합니다. 첫 번째 문자열은 어커런스를 찾고, 두 번째 인수는 시작 위치를 취합니다. 루프는 소스 문자열의 끝까지 어커런스를 찾는 데 사용됩니다.예:
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 <bits/stdc++.h>
using namespace std;
int main()
{
string s="Sakib Hossain";
int cou=count(s.begin(),s.end(),'a');
cout<<cou;
}
람다 함수를 사용하여 문자가 "_"인지 확인하면 유효한 문자가 아닌 개수 만 증가합니다.
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;
나는 이런 식으로했을 것입니다 :
#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]);
}
}
참고 URL :
https://stackoverflow.com/questions/3867890/count-character-occurrences-in-a-string-in-c
'programing' 카테고리의 다른 글
IRB 콘솔을 지우려면 어떻게합니까? (0) | 2020.05.17 |
---|---|
예외를 규칙적인 제어 흐름으로 사용하지 않는 이유는 무엇입니까? (0) | 2020.05.17 |
스팸 봇에서 이메일을 숨기는 효과적인 방법 (0) | 2020.05.17 |
대문자 앞에 공백을 추가하십시오 (0) | 2020.05.17 |
numpy 배열을 이미지로 변환하고 표시하는 방법은 무엇입니까? (0) | 2020.05.17 |