이 빠른 제안되는 링크를 -이있을 수 있습니다 더 좋은 방법이지만, 나는 이것을 좋아한다.
먼저 단어가 무엇인지 "알기"바랍니다. 문자로만 이루어진 것으로 가정 해 봅시다. 구두점 또는 "공백"인 나머지는 구분 기호로 간주 될 수 있습니다.
그런 다음 "시스템"에는 1) 단어 완성, 2) 분리 기호 건너 뛰기의 두 가지 상태가 있습니다.
건너 뛰기 구분 기호를 자유롭게 실행하여 코드를 시작하십시오. 그런 다음 다음 구분 기호 나 전체 문자열의 끝까지 보관할 "단어 완성"상태로 들어갑니다 (이 경우 종료합니다). 그런 일이 발생하면 단어를 완성 했으므로 단어 카운터를 1 씩 증가시키고 "분리 기호 건너 뛰기"상태로 들어갑니다. 그리고 루프가 계속됩니다.
의사 C 형 번호 : 판독 CHAR는 [A-ZA-Z_ 예를 들어, 그렇지 않으면 거짓 인 경우
char *str;
/* someone will assign str correctly */
word_count = 0;
state = SKIPPING;
for(c = *str; *str != '\0'; str++)
{
if (state == SKIPPING && can_be_part_of_a_word(c)) {
state = CONSUMING;
/* if you need to accumulate the letters,
here you have to push c somewhere */
}
else if (state == SKIPPING) continue; // unneeded - just to show the logic
else if (state == CONSUMING && can_be_part_of_a_word(c)) {
/* continue accumulating pushing c somewhere
or, if you don't need, ... else if kept as placeholder */
}
else if (state == CONSUMING) {
/* separator found while consuming a word:
the word ended. If you accumulated chars, you can ship
them out as "the word" */
word_count++;
state = SKIPPING;
}
}
// if the state on exit is CONSUMING you need to increment word_count:
// you can rearrange things to avoid this when the loop ends,
// if you don't like it
if (state == CONSUMING) { word_count++; /* plus ship out last word */ }
함수 can_be_part_of_a_word true를 반환.
(피곤함에 대한 심한 실수를하지 않은 경우 작동 함)
정규식을 사용할 수 없습니까? – danijar
BTW :'||'대신에'&&'를 사용해야 할 것입니다. (또는 :'! ='를'=='로 변경하고 if {}와 else {} 본문을 바꿔 넣으십시오.) – wildplasser