La función del strtok
La función del strtok se utiliza para encontrar el símbolo siguiente en una secuencia. El símbolo es especificado por una lista de delimitadores posibles.
El ejemplo siguiente lee una línea del texto de un archivo y determina una palabra usando los delimitadores, el espacio, la lengüeta, y el de giro nuevo. Cada palabra entonces se exhibe en una línea separada:
#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;
}
Sobre programa, en = fopen (“C:\ \ text.txt”, “r”), se abre y archivo existente C:\ \ text.txt. Si no existe en la trayectoria especificada o por ninguna razón, el archivo no se podría abrir, un mensaje de error se exhibe en la pantalla.
Considerar el ejemplo siguiente, que utiliza algunas de estas funciones:
#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);
}
La salida del programa será exhibida como sigue:
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? |
|