I made a program that simulates to be the function strstr
, of the library string.h
. 2 strings are entered by keyboard and the function finds the second string in the first, returning a pointer (if not found, it returns NULL
) that points to the first string (where the second is found).
I don't know how to perform the function without modifying the original string. When the function returns the "pointer" (pointer type char
that is returned to main
) and automatically modifies the original string, and I don't want that.
I hope I was clear, thank you very much in advance.
#include <stdio.h>
#include <stdlib.h>
#define TAM 30
char* mistrstr(const char*,const char*);
int main()
{
char cadena[TAM];
char cadena1[TAM];
char *aparicion;
printf("Ingrese la primer cadena:");
gets(cadena);
fflush(stdin);
printf("Ingrese la segunda cadena:");
gets(cadena1);
fflush(stdin);
aparicion=mistrstr(cadena,cadena1);
printf("Primera aparicion (con mi funcion):%s\n",aparicion);
return 0;
}
/////////////////////////////////////////////////////
char* mistrstr(const char* cadena,const char* cadena1)
{
int i=-1;
char *apuntador,*cad,*cad1;
apuntador=cadena;
cad=(char*)cadena;
cad1=(char*)cadena1;
while(*cad)
{
if(*cad1==*cad)
i=0;
else
cad++;
while(i>=0)
{
*(apuntador+i)=*cad;
i++;
cad++;
if(*cad=='\0')
{
*(apuntador+i)='\0';
return apuntador;
}
}
}
return NULL;
}
////////////////////////////////////////////////
A string, by definition, ends with a null character.
What the function
strstr
does is return a pointer to the position where the substring is... but it doesn't modify the original string :This example will return:
With this in mind, all the function does is iterate over
cadena
and, on each iteration, check to see if it finds thesubcadena
:Now, if what you want is for your function to return the substring in case it is found (ending with
'\0'
), you don't have many options:subcadena
. Technically it is what you want to return and you do not need to modify anything.cadena
. Workable and simple but you don't want to do this.In the absence of you specifying a little more what you expect, my answer ends here. My opinion is that what you want is unnecessary and artificial (if you make a function to search for a substring, what you are interested in is knowing if it is found and where... retrieving the substring is absurd because it is something that you already have stored in the substring itself ).