strtok 기능
strtok 기능은 끈에 있는 다음 토큰을 찾아내는 이용된다. 토큰은 가능한 구분짖는 기호의 명부에 의해 지정된다.
뒤에 오는 보기는 파일에서 텍스트 행을 읽고 구분짖는 기호, 공간, 탭 및 새로운 구간을 사용하여 낱말을 결정한다. 각 낱말은 개별 회선에 그 때 표시된다:
#include <stdio.h>
#include <string.h>
int main()
{
FILE *in;
char line[80];
char *delimiters = " \t\n";
char *token;
if ((in = fopen("C:\\text.txt", "r")) == NULL)
{
puts("Unable to open the input file");
return 0;
}
/* Read each line one at a time */
while(!feof(in))
{
/* Get one line */
fgets(line, 80, in);
if (!feof(in))
{
/* Break the line up into words */
token = strtok(line, delimiters);
while (token != NULL)
{
puts(token);
/* Get the next word */
token = strtok(NULL, delimiters);
}
}
}
fclose(in);
return 0;
}
프로그램의 위 그것은, 에서 = ("C:\ \ text.txt", "r") fopen, 그리고 기존 파일 C:\ \ text.txt 연다. 지정된 경로에서 또는 어떤 이유도를 위해 존재하지 않는 경우에, 파일은 스크린에, 착오 알림말 표시된다 열릴 수 없었다.
어떤을의 이 기능 사용하는 뒤에 오는 보기를 고려하십시오:
#include <stdio.h>
#include <string.h>
void main()
{
char line[100], *sub_text;
/* initialize string */
strcpy(line,"hello, I am a string;");
printf("Line: %s\n", line);
/* add to end of string */
strcat(line," what are you?");
printf("Line: %s\n", line);
/* find length of string */
/* strlen brings back */
/* length as type size_t */
printf("Length of line: %d\n", (int)strlen(line));
/* find occurence of substrings */
if ( (sub_text = strchr ( line, 'W' ) )!= NULL )
printf("String starting with \"W\" ->%s\n",
sub_text);
if ( ( sub_text = strchr ( line, 'w' ) )!= NULL )
printf("String starting with \"w\" ->%s\n",
sub_text);
if ( ( sub_text = strchr ( sub_text, 'u' ) )!= NULL )
printf("String starting with \"w\" ->%s\n",
sub_text);
}
프로그램의 산출은 다음과 같이 표시될 것이다:
Line: hello, I am a string;
Line: hello, I am a string; what are you?
Length of line: 35
String starting with "w" ->what are you?
String starting with "w" ->u? |
|