guardar palabras de una cadena en arreglos

Iniciado por bobitttyy, 4 Junio 2015, 11:23 AM

0 Miembros y 1 Visitante están viendo este tema.

bobitttyy

tenemos la cadena siguiente:
char cad[19]="esto es un mensaje";
y quiero llevaro a otro arreglo pero sus elementos son sus palabras, es decir:
char copia[4][20]={"esto","es","un","mensaje"};
#include <iostream>
#include <string.h>
using namespace std;
void main(){
char cad[80]="esto es un mensaje";
        char copia[80][20];//con[80] es longitud de cada palabra
int con[80], num_p=1,k=0;//num_p es el numero de palabras
for (int i = 0; i < strlen(cad); i++){
if (cad[i] == ' ')num_p++;
}
for (int i = 0; i < num_p; i++){
con[i] = 0;
}
num_p = 1; k = 0;
for (int i = 0; cad[i] != '\0';i++){
if (cad[i] == ' '){
num_p++; k = 0;
}
else{
cad[num_p - 1]++;
copia[num_p - 1][k++] = cad[i];
}
}
for (int i = 0; i < num_p; i++){
cout << copia[i] << "\n";
}
system("PAUSE");
}

se que hay un metodo de los tokens, pero yo quiero sin eso....consejos por favor

user-marcos

Código (cpp) [Seleccionar]

#include <iostream>
#include <string.h>
using namespace std;
int  main()
{
  char cad[80]="y esto es un mensaje";
  char copia[20][80];
  int cont = 0;
  int it=0;

  for (int i = 0; i < strlen(cad); i++)
    {
      if(cad[i] != ' '){
copia[cont][it] = cad[i];
it++;
}
      else
      { copia[cont][it+1]= '\0';
cont++;
it = 0;
      }
    }

 
   for(int i = 0; i < cont+1; i++)
   { cout << endl;
     for(int j = 0; j < strlen(copia[i]); j++)
       cout << copia[i][j];
  }
 
}
 

bobitttyy

Cita de: user-marcos en  4 Junio 2015, 16:50 PM
Código (cpp) [Seleccionar]

#include <iostream>
#include <string.h>
using namespace std;
int  main()
{
  char cad[80]="y esto es un mensaje";
  char copia[20][80];
  int cont = 0;
  int it=0;

  for (int i = 0; i < strlen(cad); i++)
    {
      if(cad[i] != ' '){
copia[cont][it] = cad[i];
it++;
}
      else
      { copia[cont][it+1]= '\0';
cont++;
it = 0;
      }
    }

 
   for(int i = 0; i < cont+1; i++)
   { cout << endl;
     for(int j = 0; j < strlen(copia[i]); j++)
       cout << copia[i][j];
  }
 
}
 


gracias....me ayudo mucho

ThunderCls

Código (cpp) [Seleccionar]
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}


AQUI puedes aclararte mas
Saludos
-[ "...I can only show you the door. You're the one that has to walk through it." – Morpheus (The Matrix) ]-
http://reversec0de.wordpress.com
https://github.com/ThunderCls/

antoniognzle

Tambien puedes utilzar las funciones STR, y en este caso strcpy
..:: xMast3r ::..