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 ????
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 ????
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;
}
The previous solution uses pointers for two things:
=
is stored. The memory locations must be saved in pointers. 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:
=
, that instead of returning the address where it is, return the index (integer) inside the array. 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).