separate words entered in a char

-2

I'm doing a few exercises in which I have to compare words from a string of characters entered by the user, in an exercise I have to see how many times a word is repeated in the whole chain that the user entered and in another exercise I have to see if a word has IE , if it has it, I have to print that word in specific.

The problem here is that I have no idea how to separate words from all char to then be able to work with the words separately.

How can I separate the words entered, according to what I describe in my question?

This is the code:

#include <stdio.h>
#include <stdlib.h>

int main()
{//Programa para ver frecuencia de palabras
char cadena[60];
int i,j;//Controladores de los ciclos for
printf("Ingresa una oracion\n");
scanf("%[^\n]"&cadena);

return 0;
}
    
asked by Cristian Alvarez 24.03.2017 в 20:52
source

1 answer

1

To separate the words you can use strtok or iterate over the string looking for characters other than letters (spaces, commas, points, ...).

  

In an exercise I have to see how many times a chain word that the user entered is repeated

If the exercise is not excessively puñetero mixing letters, numbers and diverse symbols (point, comma, semicolon, hyphens, parentheses, etc ...) the simplest would be to break the input string with strtok and compare each substring with the initial word:

const char* ptr = strtok(cadena," ,.");
while( ptr != 0 )
{
  if( strcmp(ptr,palabraABuscar) == 0 )
    printf("BINGO!!!\n");
  ptr = strtok(NULL," ,.");
}
  

In another exercise I have to see if a word has IE, if it has one, I have to print that word in specific

You can use the same logic but replace strcmp with a function that searches for substrings, such as strstr :

const char* cadena = "abcdefg";
if( strstr(cadena,"bc" ) != NULL )
  printf("subcadena bc encontrada\n");
else
  printf("subcadena bc NO encontrada\n");

if( strstr(cadena,"bb" ) != NULL )
  printf("subcadena bb encontrada\n");
else
  printf("subcadena bb NO encontrada\n");
    
answered by 03.04.2017 в 11:32