// Estas leyendo...

C \\ C++

Funcion Split / Strtok C++

Funcion que sirve para partir cadenas de texto usando separadores, muy util para lanzar comandos con parametros, un ejemplo podria ser el uso de comandos en una herramienta que utiliza sockets, podemos enviar char arrays del tipo: comando-parametro1-parametro2 en texto plano atraves del socket o cualquier otro medio.

#include <cstdlib>
#include <stdio.h>
#include <windows.h>

/* ///////////////////////////////////////////////////////////////
/*
/*  Funcion Split con strtok
/*  By Octalh
/*  www.aztekmindz.org | octalh@gmail.com
/*  USO: cmd("CADENA-DE-TEXTO","SEPARADOR",TROZO_DECEADO)
/*  Ejemplo: char* msj = cmd("salu2-desde-aztekmindz","-",2);
/*  msj es igual a: "aztekmindz"
/*  Los trozos se cuentan desde el "0".
/*
*/
///////////////////////////////////////////////////////////////

using namespace std;

int cc( char* strc, char sep ){
   int cc = 0;
   while( *strc ){
      if((char)*strc == (int)sep){
         cc++;
      }
      strc++;
   }
   return cc;
}

char *cmd(char *str2,char *sep, int prt){
      static char salida[100];
      char str[100];
      strcpy(str,str2);
      int cuantas = cc( str,sep[0]);
      char *test[100];
      test[0] = strtok(str, sep);
      if (prt == 0){
           if(cuantas != 0){
              sprintf(salida,"%s",test[0]);
           }else{
              sprintf(salida,"ERROR");
           }

      }else{
         if (cuantas+1 > prt ){
             for(int i = 1; i < prt+1; i++){
                test[i] = strtok (NULL, sep);
                sprintf(salida,"%s",test[i]);
             }
         }else{
             sprintf(salida,"ERROR");
         }
      }
return salida;
}

int main(int argc, char *argv[])
{  

    char* msj = cmd("A-B-C-D-E","-",2);
    printf("%s \n",msj);
    system("PAUSE");
    return EXIT_SUCCESS;
}

.

Comentarios

No hay comentarios para “Funcion Split / Strtok C++”

Deja un comentario