How to extract a string inside a string in c? [closed]

0

I have the following string:

 char url[]="table=peliculas/&name=lo_que_sea.pdf"

I want to store "what_that_is_.pdf" in a variable like that text would be different from my string ????

    
asked by ortiga 15.12.2018 в 17:16
source

1 answer

1

The easiest thing to do is to find the memory address where the last = of the string is stored (using strrchr() ) and copy to another chain what is there from that point (using for example strdup() ) .

For example:

#include <stdio.h>
#include <string.h>

int main() {
  char url[]="table=peliculas/&name=lo_que_sea.pdf";
  char *nombre_fichero;
  char *pos_igual;

  pos_igual = strrchr(url, '=');
  if (pos_igual == 0) {
    printf("La URL no tiene el formato esperado\n");
  } else {
    nombre_fichero = strdup(pos_igual+1);
    printf("Nombre del fichero: %s\n", nombre_fichero);
  }
  return 0;
}

No pointers (well, almost)

The previous solution uses pointers for two things:

  • To find the memory location inside the url where the last = is stored. The memory locations must be saved in pointers.
  • To obtain a copy of the part that contains the name of the file. The copies must be made to another memory location, whose size we do not know in advance because we do not know how many letters the file name will have, so we can not reserve an array for it. The function strdup() "duplicates" a string (or substring in this case) making space for the new one, and returning the memory address where it was copied. This address is again a pointer.
  • You can delete the pointers if:

  • We program our own function to find the = , that instead of returning the address where it is, return the index (integer) inside the array.
  • We do not take copy of the file name, but only print it.
  • This solution does that:

    #include <stdio.h>
    #include <string.h>
    
    int indice_del_ultimo(char cadena[], char buscar) {
      int i;
    
      for (i=strlen(cadena); i>=0; i--) {
        if (cadena[i] == buscar)
          return i;
      }
      return -1; // No se ha encontrado
    }
    
    int main() {
      char url[]="table=peliculas/&name=lo_que_sea.pdf";
      //char nombre_fichero[];
      int pos_igual;
    
      pos_igual = indice_del_ultimo(url, '=');
      if (pos_igual == -1) {
        printf("La URL no tiene el formato esperado\n");
      } else {
        printf("Nombre del fichero: %s\n", url+pos_igual+1);
      }
      return 0;
    }
    

    Although apparently pointers have not been used (there are no variables of type char* ), in fact there is arithmetic of pointers in the expression url+pos_igual+1 , since the result of that is a memory address (specifically, the address where is the letter following the = found in the URL).

        
    answered by 15.12.2018 / 17:27
    source