Funcion instr o strpos

Iniciado por linkgl, Agosto 17, 2011, 12:35:12 PM

Tema anterior - Siguiente tema

0 Miembros y 2 Visitantes están viendo este tema.

Buenas, supongo que conocen la funcion strpos de PHP y la función instr de vb, bueno para el que no, estas funciones buscan una cadena o string, dentro de otra y devuelven la posición en donde se encontró el primer caracter de la cadena a buscar :P

ejemplo
buscar="hola"
cadena="linkholalink"
strpos(cadena,buscar)
Me debe devolver 5

pues hice esta función en C.

Código: c
/*
  @Coder: Linkgl
    @Funcion: Instr o StrPos */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//prototipo
int instr(char *cadena,char *necesitada);

//->uso
int main()
{
  int x=instr("linkholalink","hola");
  printf("%d",x);
  getchar();
  return 0;
}

//funcion
int instr(char *cadena,char *necesitada)
{
  int iCadena=strlen(cadena);
  int iNecesitada=strlen(necesitada);
  int i;
  char *temp=(char *)malloc(iNecesitada);
  memset(temp,0,iNecesitada);
  for(i=0;i<iCadena*iNecesitada;i++)
  {
    memcpy(temp,cadena+i,iNecesitada);
    if(strcmp((char *)necesitada,(char *)temp)==0)
    {
      free(temp);
      return i+1;     
    }
  }
  free(temp);
  return -1;
}


PD: Me faltan valores negativos  :-\

Ya existe esta función,

You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login

saludos
You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login

You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login
Ya existe esta función,

You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login

saludos

JA. En aquel entonces podría jurar que la busqué en cplusplus y sólo encontré strtok y no me valía igual, pero toda la razón. Saludos

You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login
You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login
Ya existe esta función,

You are not allowed to view links. You are not allowed to view links. Register or Login or You are not allowed to view links. Register or Login

saludos

Hostia linkgl, ¿vuelves al foro?
JA. En aquel entonces podría jurar que la busqué en cplusplus y sólo encontré strtok y no me valía igual, pero toda la razón. Saludos
Twitter: @The_Pr0ph3t
[email protected]

Haha estuve fuera de todo esto un buen rato, pero cualquier cosilla ya andamos aquí.  :o