검색결과 리스트
프로그래밍에 해당되는 글 84건
- 2012.03.18 [C++] 입력한 문자열을 분석하여 단어 카운트하기
글
간단한 C++ 예제입니다. 콘솔창에서 사용자에게 문자열을 ctrl+z 입력 전까지 입력받고, 그 입력 받은 문자열을 space bar 만큼 잘라서 몇 번 중복하는지 카운트하는 프로그램입니다. 특별히 들어간 문법이라고 한다면 struct, verctor, templet, 함수 정도 됩니다. 쉬운 예제이니 한 번 타이핑 하면서 이해하는 것도 공부에 도움이 됩니다.
CountWords.cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct WORD {
string str;
int count;
};
vector <WORD*> words;
int FindWords(const string& s);
void CountWords(const string& s);
void ShowWords();
void RemoveAll();
int main() {
cout << "문자열을 입력하세요. 입력을 마쳤으면 Ctrl+z 을 누르세요." << endl;
string buffer;
while( cin >> buffer)
CountWords(buffer);
ShowWords();
RemoveAll();
return 0;
}
void CountWords(const string& s) {
int index = FindWords(s);
if(index == -1) {
WORD *pWord = new WORD;
pWord->str = s;
pWord->count = 1;
words.push_back(pWord);
}
else {
words[index]->count++;
}
}
int FindWords(const string& s) {
for(int i = 0; i<words.size(); i++){
if(words[i]->str == s)
return i;
}
return -1;
}
void ShowWords() {
for(int i=0; i<words.size(); i++)
cout << words[i]->str << " : " << words[i]->count << "번" << endl;
}
void RemoveAll() {
for(int i=0; i<words.size(); i++)
delete words[i];
}
- 실행 콘솔창
- 실행 콘솔창
'프로그래밍 > ㆍC/C++/Java' 카테고리의 다른 글
[java] 별(*) 여러가지 모양으로 출력하기 - 반복문 ( 삼각형, 피라미드, 다이아몬드 ) (0) | 2012.03.19 |
---|---|
[C++] 객체에 대한 포인터 배열의 생성 - 간단한 예제 (0) | 2012.03.18 |
[C] 비주얼 스튜디오 11로 C언어를 시작해보자 - Hello World (2) | 2012.03.18 |
[java] 주어진 정수를 각 자리로 나누어 출력하기 (4) | 2012.03.15 |
RECENT COMMENT