2012-09-11 2 views
0

문자열에있는 단어의 수를 찾는 코드를 작성합니다. 각 단어를 다른 문자로 구분할 수 있음을 알고 있습니다. AZ (또는 az). 내가 작성한 코드는 문장의 시작 부분에 문장 부호가없는 경우에만 잘 작동합니다. 그러나 문제는 따옴표와 같이 구두점을 사용하여 문장을 시작할 때 발생합니다 (예 : "연결 만하십시오."는 결과가 2 대신 3 단어로 표시됨). 저는 Dev-C++을 사용하여 C++로 프로그래밍하고 있습니다. 귀하의 도움을 주시면 감사하겠습니다. 내 코드는 다음과 같습니다.문자열의 정확한 단어 수가 인용 부호와 같은 구두점으로 시작되지 않음

#include <cstring> 
#include <iostream> 
#include <conio.h> 
#include <ctype.h> 

using namespace std; 

int getline(); //scope 
int all_words(char prose[]); //scope 

int main() 
{ 
    getline(); 
    system ("Pause"); 
    return 0; 
} 


int getline() 
{ 
    char prose[600]; 
    cout << "Enter a sentence: "; 

    cin.getline (prose, 600); 
    all_words(prose); 
    return 0; 
} 


int all_words(char prose[]) 
{ int y, i=0, k=0; int count_words=0; char array_words[600], c; 

    do 
    { 

     y=prose[i++]; 
     if (ispunct(y)) //skeep the punctuation 
     i++; 

     if ((y<65 && isspace(y)) || (y<65 && ispunct(y)))  //Case where we meet spacial character or punctuation follwed by space 

      count_words++; //count words 

     if (ispunct(y)) //skeep the punctuation 
      i++; 

    }while (y); //till we have a character 

    cout <<endl<<" here is the number of words "<< count_words <<endl; 

    return 0; 

} 



***********************************Output****************************** 
    Enter a sentence: "Only connect!" 

    here is the number of words 3 

    Press any key to continue . . . 
+0

답변 [1]을 (를) 당신의 질문에 답하십시오. [1] : http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c –

답변

2

알고리즘을 다시 생각해보십시오. 내 머리 위로, 나는 그것을 이런 식으로 뭔가 할 수 있습니다

  • 루프
    • 건너 뛰기 문자열의 모든 알파벳이 아닌 문자 (while (!std::isalpha))
    • 모든 알파벳 문자를 건너 뜁니다을 종료하지 않으면 서 (while (std::isalpha)를)
    • 증가 워드 카운터

최종 확인하는 것을 잊지 마십시오 그 내부 고리에있는 끈의 당신이 증가 카운터 난을했지만, var에 y는 여전히 ". 참으로 두 번째 조건을 얻을 수있는 마지막 하나"를 포함 첫번째 따옴표에

if (ispunct(y)) 

먼저

0

당신에게 ++ count_words에 추가 증가를 제공합니다;

if ((y<65 && isspace(y)) || (y<65 && ispunct(y))) 

어쨌든 작업은 문자열을 토큰으로 분할하여 계산하는 것입니다. 예제 솔루션은 여기 here에서 찾을 수 있습니다.