C++ 문자열에서 발생한 문자 수
의 수를 어떻게 셀 수 있습니까?"_"
같은 줄로"bla_bla_blabla_bla"
?
#include <algorithm>
std::string s = "a_b_c";
std::string::difference_type 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년 후, 이 답변을 보면, 나는 이것을 한 것이 부끄럽습니다(나 스스로 낮은 노력을 요하는 질문에 대한 비꼬는 것으로 정당화 되었음에도 불구하고).이것은 독성이 있고 괜찮지 않다.게시물을 삭제하는 것이 아니라 StackOverflow 분위기 전환을 돕기 위해 이 사과를 추가합니다.OP: 사과드립니다.제 트롤링에도 불구하고 숙제를 제대로 하셨는지, 제 답변과 같은 답변이 사이트에 참여하는 것을 주저하지 않으셨는지 모르겠습니다.
lamda 함수를 사용하여 문자가 "_"인지 확인하면 카운트가 증가하며, 그렇지 않으면 유효한 문자가 아닙니다.
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;
#include <boost/range/algorithm/count.hpp>
std::string str = "a_b_c";
int cnt = boost::count(str, '_');
뭐든 말해 봐...람다 버전...:)
using namespace boost::lambda;
std::string s = "a_b_c";
std::cout << std::count_if (s.begin(), s.end(), _1 == '_') << std::endl;
여러 가지가 필요합니다.연습 삼아 남겨두죠
문자열에서 발생한 문자 수를 쉽게 계산할 수 있습니다.
#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에는 여러 가지 검색 방법이 있지만 찾고 있는 방법이 있을 수 있습니다.C 스타일 문자열을 의미하는 경우 strchr이 됩니다.단, 어느 경우든 for 루프를 사용하여 각 문자를 체크할 수도 있습니다.루프는 기본적으로 이들2개의 랩업입니다.
주어진 시작 위치에서 다음 문자를 찾는 방법을 알게 되면 검색(루프 사용 등)을 계속 진행하여 진행하면서 숫자를 셀 수 있습니다.
이런 식으로 했을 거예요.
#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;
}
문자열 함수를 사용하면 소스 문자열에 '_'가 있는지 확인할 수 있습니다.find() 함수는 두 개의 인수를 사용합니다.첫 번째 문자열은 발생 상황을 파악하고 두 번째 인수가 시작 위치를 차지합니다.한편, 루프는 소스 문자열의 마지막까지 오카렌스를 검출하기 위해서 사용됩니다.
예:
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();
}
루프에 기반한 범위는 편리합니다.
int countUnderScores(string str)
{
int count = 0;
for (char c: str)
if (c == '_') count++;
return count;
}
int main()
{
string str = "bla_bla_blabla_bla";
int count = countUnderScores(str);
cout << count << endl;
}
나도 그런 짓을 했을 거야:)
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' 카테고리의 다른 글
이전 bash 명령어 인수를 호출하려면 어떻게 해야 합니까? (0) | 2023.04.10 |
---|---|
YAML 어레이를 Marge하는 방법 (0) | 2023.04.10 |
로컬 변경을 무시한 채 git pull을 하려면 어떻게 해야 합니까? (0) | 2023.04.10 |
UIView의 고정 높이 구속조건을 프로그래밍 방식으로 업데이트하려면 어떻게 해야 합니까? (0) | 2023.04.10 |
SDF 파일(SQL Server Compact Edition)을 열려면 어떻게 해야 합니까? (0) | 2023.04.10 |