큰 문자열을 작은 문자열 (단어)로 분리하여 설명합니다. 당신을 가정
는 공백이나 탭이나 줄 바꿈으로, 구문 분석하는 일반적인 구분 기호를 사용하고 있습니다 :
먼저는, 소스 문자열에 대한 정보를 얻을 :
여기
는 세 단계 접근에게 있습니다.
둘째, 당신의 크기는 문자열의 대상 배열을 채울 strtok()
에
셋째, 루프를 필요에 맞게 동적으로 대상 배열을 생성 (문자 **)
(A 등이 될 것이다 생성 된 메모리를 해제하려면, 당신이해야 할 것입니다)
힌트 : 프로토 타입은 다음과 같이 보일 수 있습니다 :
// void Free2DCharArray (char ** a, int numWords);
코드 예제 :
이
void FindWords(char **words, char *source);
void GetStringParams(char *source, int *longest, int *wordCount);
char ** Create2DCharArray(char **a, int numWords, int maxWordLen);
#define DELIM " \n\t"
int main(void)
{
int longestWord = 0, WordCount = 0;
char **words={0};
char string[]="this is a bunch of test words";
//Get number of words, and longest word, use in allocating memory
GetStringParams(string, &longestWord, &WordCount);
//create array of strings with information from source string
words = Create2DCharArray(words, WordCount, longestWord);
//populate array of strings with words
FindWords(words, string);
//Do not forget to free words (left for you to do)
return 0;
}
void GetStringParams(char *source, int *longest, int *wordCount)
{
char *tok;
int i=-1, Len = 0, KeepLen = 0;
char *cpyString = 0;
cpyString = calloc(strlen(source)+1, 1);
strcpy(cpyString, source);
tok=strtok(source, DELIM);
while(tok)
{
(*wordCount)++;
Len = strlen(tok);
if(Len > KeepLen) KeepLen = Len;
tok = strtok(NULL, DELIM);
}
*longest = KeepLen;
strcpy(source, cpyString);//restore contents of source
}
void FindWords(char **words, char *source)
{
char *tok;
int i=-1;
tok = strtok(source, DELIM);
while(tok)
{
strcpy(words[++i], tok);
tok = strtok(NULL, DELIM);
}
}
char ** Create2DCharArray(char **a, int numWords, int maxWordLen)
{
int i;
a = calloc(numWords, sizeof(char *));
if(!a) return a;
for(i=0;i<numWords;i++)
{
a[i] = calloc(maxWordLen + 1, 1);
}
return a;
}
마법 번호와 비교하지 마십시오. 'isalpha()'와''-''를 사용하십시오. – unwind
귀하의 질문은 [this one] (http://stackoverflow.com/questions/308695/how-to-html)과 중복되는 [this one] (http://stackoverflow.com/q/26869798/841108)과 유사합니다. concatenate-const-literal-strings-in-c). [내 대답] (http://stackoverflow.com/a/26869883/841108)을 필요에 맞게 수정하십시오. –
현재'wordToCheck' 배열을 채 웁니다 (그러나'= ""이니셜 라이저를 제거합니다. 전역 변수는'zero initialized '입니다.) 그래서'tmp'가 너무 길지 않다면 배열에 NUL 종료 문자열을 얻을 것입니다.) 전역 변수이므로 다른 함수에서 액세스 할 수 있습니다. 원하는 것을 명확히하거나 문제가 무엇인지 명확히하십시오. – Jite