La fonction de strtok
La fonction de strtok est employée pour trouver la prochaine marque dans une corde. La marque est indiquée par une liste de délimiteurs possibles.
L'exemple suivant lit une ligne de texte à partir d'un dossier et détermine un mot en utilisant les délimiteurs, l'espace, l'étiquette, et le d'interligne. Chaque mot est alors montré sur une ligne séparée :
#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;
}
Il au-dessus du programme, dans = fopen (" C:\ \ text.txt ", " r "), s'ouvre et dossier existant C:\ \ text.txt. Si n'existe dans le chemin indiqué ou pour aucune raison, le dossier ne pourrait pas être ouvert, un message d'erreur est montré sur l'écran.
Considérer l'exemple suivant, qui emploie certaines de ces fonctions :
#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);
}
Le rendement du programme sera montré comme suit :
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? |
|