separar una oración en palabras

  • fish
  • Newbie
  • Newbie
  • No Avatar
  • Registrado: Mar 29, 2003
  • Mensajes: 5
  • Status: Offline

Nota Abril 4th, 2003, 4:16 pm

Hola,

Yo estaba tras alguna sugerencia en cuanto a cómo podría i

-- Aceptar una condena por parte del usuario

-- Entonces cada palabra de esa oración y lo mostrará en orden inverso, pero no invertir el orden de la totalidad de la frase.

Yo estaba pensando que hasta el bucle \ 0 - final de la línea
entonces dentro de ese bucle, bucle i hasta alcanzar un - espacio. cuando se llega a un espacio I - crear otra función para revertir esa palabra, y luego volver al bucle hasta el siguiente espacio.

Esperanza lo que he dicho tiene sentido!

anyhelp serán bienvenidos.

Gracias
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Abril 4th, 2003, 4:16 pm

  • Bigwebmaster
  • Site Admin
  • Site Admin
  • Avatar de Usuario
  • Registrado: Dic 20, 2002
  • Mensajes: 8934
  • Loc: Seattle, WA & Phoenix, AZ
  • Status: Offline

Nota Abril 4th, 2003, 4:27 pm

Si se trata de mí lo que me gustaría hacer es en primer lugar todos los caracteres introducidos por el usuario y el lugar en una matriz. (Si la matriz impresa en el orden que obtendría el sentece que mecanografiadas).

En segundo lugar quisiera entonces para ejecutar un bucle en la matriz que hubiera otro bucle anidado. El bucle exterior se iniciaría a partir del final de la serie y el trabajo de vuelta al comienzo de la matriz. Una vez que hayas encontrado el primer espacio en el exterior del bucle entonces su interior bucle se ejecutaría en el terreno actual en la matriz e imprimir caracteres.

Nota - usted probablemente necesita dos contadores variables. Una perder de vista su posición de partida para la impresión en conjunto, y una segunda para llevar un registro de la posición en que terminó la serie en la que debe imprimir.

De todos modos estoy seguro de que hay muchas maneras en que puede lograr este objetivo, que es lo que yo intente sin embargo.

Ahora, si usted puede utilizar C + +, sería mucho más sencillo. Me limitaré a añadir todos los caracteres ingresados a una cadena. En ese momento me limitaré a hacer una inversión para encontrar encontrar los espacios y dividir cada palabra y cada palabra lugar en una matriz, para que yo podría entonces la matriz de impresión hacia atrás en ese punto.
Ozzu Hosting - Want your website on a fast server like Ozzu?
  • fish
  • Newbie
  • Newbie
  • No Avatar
  • Registrado: Mar 29, 2003
  • Mensajes: 5
  • Status: Offline

Nota Abril 4th, 2003, 6:22 pm

gracias por la ayuda.

¿Podría usted por favor me da una idea de cómo codificar lo que puso en su entrada, como se indica en el anterior hilo Soy un verdadero "NOVICE".

gracias
  • fish
  • Newbie
  • Newbie
  • No Avatar
  • Registrado: Mar 29, 2003
  • Mensajes: 5
  • Status: Offline

Nota Abril 4th, 2003, 7:51 pm

Esto es lo que tengo hasta ahora, pero no puedo averiguar cómo poner cada palabra en una nueva matriz

Código: [ Select ]
int reverseWords()
{
    char whole_line[MAX_LINE];
    char word[MAX_LINE];
    int i;

    printf("%s", "\nEnter a line of text (upto 50 characters): \n");
    fgets(whole_line, MAX_LINE, stdin);

    for(i = 0; i < MAX_LINE, whole_line[i] !=''; i++)
    putchar(whole_line[i]);
    
    
    if(whole_line[i] == ' ')
    {
        strcpy(word, whole_line); <-- how can i pass in just the word and not the whole line???
        printf("word in if --> %s",word);
            }
        return 0;
}
  1. int reverseWords()
  2. {
  3.     char whole_line[MAX_LINE];
  4.     char word[MAX_LINE];
  5.     int i;
  6.     printf("%s", "\nEnter a line of text (upto 50 characters): \n");
  7.     fgets(whole_line, MAX_LINE, stdin);
  8.     for(i = 0; i < MAX_LINE, whole_line[i] !=''; i++)
  9.     putchar(whole_line[i]);
  10.     
  11.     
  12.     if(whole_line[i] == ' ')
  13.     {
  14.         strcpy(word, whole_line); <-- how can i pass in just the word and not the whole line???
  15.         printf("word in if --> %s",word);
  16.             }
  17.         return 0;
  18. }


gracias
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • Avatar de Usuario
  • Registrado: Dic 20, 2002
  • Mensajes: 8934
  • Loc: Seattle, WA & Phoenix, AZ
  • Status: Offline

Nota Abril 4th, 2003, 8:36 pm

En lugar de usign strcpy para copiar los caracteres de su whole_line intente utilizar strncpy como puede especificar la longitud exacta de copiar. Sin embargo, usted van a tener que averiguar cuál es la longitud que desee copiar, lo que significa que usted tendrá que calcular la longitud de la palabra de alguna manera. De todas formas para obtener más información acerca de strncpy salir antes de este enlace:

http://www.cplusplus.com/ref/cstring/strncpy.html
Ozzu Hosting - Want your website on a fast server like Ozzu?
  • RichB
  • Guru
  • Guru
  • Avatar de Usuario
  • Registrado: May 17, 2003
  • Mensajes: 1121
  • Loc: Boston
  • Status: Offline

Nota Junio 19th, 2003, 5:19 am

Código: [ Select ]
/*
This is obviously too late to help the original poster, but I figure other people might view the topic and anyway I'm a bit rusty in C, so this seemed like a good problem to get back into it. This was my solution.
*/

#include <stdio.h>
#include <string.h>

int main(void)
{
int length,last,start = 0;
char c,string[100];

printf("Enter a string: ");
gets(string);

length = strlen(string)+1;

    for(int i=0; i<length; i++)
    {
        c = string[i];

        if(c == ' ' || c=='')
        {
            last = i-1;

            for(int j=0; j<i-start; j++)
            {
                putchar(string[last--]);
            }
            if(c!='')
            {
                putchar(' ');
            }

            start = i+1;
        }
    }
return 0;
}
  1. /*
  2. This is obviously too late to help the original poster, but I figure other people might view the topic and anyway I'm a bit rusty in C, so this seemed like a good problem to get back into it. This was my solution.
  3. */
  4. #include <stdio.h>
  5. #include <string.h>
  6. int main(void)
  7. {
  8. int length,last,start = 0;
  9. char c,string[100];
  10. printf("Enter a string: ");
  11. gets(string);
  12. length = strlen(string)+1;
  13.     for(int i=0; i<length; i++)
  14.     {
  15.         c = string[i];
  16.         if(c == ' ' || c=='')
  17.         {
  18.             last = i-1;
  19.             for(int j=0; j<i-start; j++)
  20.             {
  21.                 putchar(string[last--]);
  22.             }
  23.             if(c!='')
  24.             {
  25.                 putchar(' ');
  26.             }
  27.             start = i+1;
  28.         }
  29.     }
  30. return 0;
  31. }
Free Programming Resources
  • RichB
  • Guru
  • Guru
  • Avatar de Usuario
  • Registrado: May 17, 2003
  • Mensajes: 1121
  • Loc: Boston
  • Status: Offline

Nota Junio 19th, 2003, 5:40 am

Código: [ Select ]
/*
If you were supposed to modify the original string by reversing the interior strings without reversing the whole thing, then I would do it like this.
*/

#include <stdio.h>
#include <string.h>

int main(void)
{
int length,start = 0,last,first;
char c,temp,string[100];

printf("Enter a string: ");
gets(string);

length = strlen(string)+1;

    for(int i=0; i<length; i++)
    {
        c = string[i];

        if(c == ' ' || c=='')
        {
            last=i-1;
            first=start;
            for(int j=0; j<(i-start)/2; j++)
            {
                temp = string[first];
                string[first] = string[last];
                string[last] = temp;
                last--;
                first++;
            }
            start = i+1;
        }
    }
printf("%s\n",string);
return 0;
}
  1. /*
  2. If you were supposed to modify the original string by reversing the interior strings without reversing the whole thing, then I would do it like this.
  3. */
  4. #include <stdio.h>
  5. #include <string.h>
  6. int main(void)
  7. {
  8. int length,start = 0,last,first;
  9. char c,temp,string[100];
  10. printf("Enter a string: ");
  11. gets(string);
  12. length = strlen(string)+1;
  13.     for(int i=0; i<length; i++)
  14.     {
  15.         c = string[i];
  16.         if(c == ' ' || c=='')
  17.         {
  18.             last=i-1;
  19.             first=start;
  20.             for(int j=0; j<(i-start)/2; j++)
  21.             {
  22.                 temp = string[first];
  23.                 string[first] = string[last];
  24.                 string[last] = temp;
  25.                 last--;
  26.                 first++;
  27.             }
  28.             start = i+1;
  29.         }
  30.     }
  31. printf("%s\n",string);
  32. return 0;
  33. }
Free Programming Resources
  • RichB
  • Guru
  • Guru
  • Avatar de Usuario
  • Registrado: May 17, 2003
  • Mensajes: 1121
  • Loc: Boston
  • Status: Offline

Nota Junio 19th, 2003, 6:04 am

Código: [ Select ]
/*
As bigwebmaster pointed out it's a lot easier in an OOP language that has a string data type. Here's the second version in java w/out user input.
*/

import java.util.StringTokenizer;
public class Test
{
    public static void main(String[] args){
        String strings = "one two three four five six seven";
        StringTokenizer chopper = new StringTokenizer(strings);
        strings = "";
        while(chopper.hasMoreTokens()){
            strings += new StringBuffer(chopper.nextToken()).reverse().toString();
            strings +=" ";
        }
        strings = strings.trim();
        System.out.println(strings);
    }
}
  1. /*
  2. As bigwebmaster pointed out it's a lot easier in an OOP language that has a string data type. Here's the second version in java w/out user input.
  3. */
  4. import java.util.StringTokenizer;
  5. public class Test
  6. {
  7.     public static void main(String[] args){
  8.         String strings = "one two three four five six seven";
  9.         StringTokenizer chopper = new StringTokenizer(strings);
  10.         strings = "";
  11.         while(chopper.hasMoreTokens()){
  12.             strings += new StringBuffer(chopper.nextToken()).reverse().toString();
  13.             strings +=" ";
  14.         }
  15.         strings = strings.trim();
  16.         System.out.println(strings);
  17.     }
  18. }
Free Programming Resources
  • RichB
  • Guru
  • Guru
  • Avatar de Usuario
  • Registrado: May 17, 2003
  • Mensajes: 1121
  • Loc: Boston
  • Status: Offline

Nota Junio 19th, 2003, 11:22 am

Código: [ Select ]
/*
I may have misunderstood the problem
the above examples take a string like "one two three" and output "eno owt eerht"
to get "three two one" I came up with this and it seemed to work
*/

#include <stdio.h>
#include <string.h>

int main(void)
{
    int length,letter;
    char c,string[100];

    printf("Enter a string: ");
    gets(string);

    length = strlen(string);

    for(int i=length; i>=0; i--)
    {
        c = string[i];
        
        if(c == ' ' || i==0)
        {
            if(i==0)
            {
                letter = i;
            }
            else
            {
                letter = i+1;
            }
            c=string[letter];
            while((c !='') && (c !=' '))
            {
                putchar(string[letter]);
                letter++;
                c=string[letter];
            }
            if(i!=0)
            {
                putchar(' ');
            }
        }
    }
    return 0;
}
  1. /*
  2. I may have misunderstood the problem
  3. the above examples take a string like "one two three" and output "eno owt eerht"
  4. to get "three two one" I came up with this and it seemed to work
  5. */
  6. #include <stdio.h>
  7. #include <string.h>
  8. int main(void)
  9. {
  10.     int length,letter;
  11.     char c,string[100];
  12.     printf("Enter a string: ");
  13.     gets(string);
  14.     length = strlen(string);
  15.     for(int i=length; i>=0; i--)
  16.     {
  17.         c = string[i];
  18.         
  19.         if(c == ' ' || i==0)
  20.         {
  21.             if(i==0)
  22.             {
  23.                 letter = i;
  24.             }
  25.             else
  26.             {
  27.                 letter = i+1;
  28.             }
  29.             c=string[letter];
  30.             while((c !='') && (c !=' '))
  31.             {
  32.                 putchar(string[letter]);
  33.                 letter++;
  34.                 c=string[letter];
  35.             }
  36.             if(i!=0)
  37.             {
  38.                 putchar(' ');
  39.             }
  40.         }
  41.     }
  42.     return 0;
  43. }
Free Programming Resources
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • Avatar de Usuario
  • Registrado: Dic 20, 2002
  • Mensajes: 8934
  • Loc: Seattle, WA & Phoenix, AZ
  • Status: Offline

Nota Junio 19th, 2003, 12:18 pm

Muy bien, creo que esta información adicional podría ser útil para algunos :)
Ozzu Hosting - Want your website on a fast server like Ozzu?
  • UNFLUX
  • Genius
  • Genius
  • Avatar de Usuario
  • Registrado: Dic 20, 2002
  • Mensajes: 6382
  • Loc: twitter.com/unflux
  • Status: Offline

Nota Junio 19th, 2003, 2:45 pm

no significa nada para mí. Yo esperaba ver a las penas, y todo lo que puedo ver es un
montón de símbolos y letras y personajes y cosas...:P
UNFLUX.FOTO
  • RichB
  • Guru
  • Guru
  • Avatar de Usuario
  • Registrado: May 17, 2003
  • Mensajes: 1121
  • Loc: Boston
  • Status: Offline

Nota Junio 19th, 2003, 10:42 pm

Código: [ Select ]
/*
I hope you mean that the code looks like gibberish and not that you ran the code and the result was gibberish. Anyway, here is the first version properly commented - the others versions are just variations on the same theme - except for java which is a horse of a different color.
*/
#include <stdio.h>
#include <string.h>

int main(void)
{
int length,last,start = 0;
char c,string[100];

//prompt the user and input the string
printf("Enter a string: ");
gets(string);

//get the string's length and add 1 for the null terminator - ''
length = strlen(string)+1;

    //the outer loop will "walk" over the whole string
  for(int i=0; i<length; i++)
  {
      //extract a letter each "step"
   c = string[i];
     
     //if the letter is a space or the null terminator start reversing
   if(c == ' ' || c=='')
   {
         //"i" will point to the space between the words or the '' at the end
         //of the sentence so go back one for the last letter of the word
     last = i-1;
        
         //start will be 0 the first time so i-start will hold the length
         //that we need to reverse and we will change start afterwards
     for(int j=0; j<i-start; j++)
     {
             //put the letter to the output and step back one each time
      putchar(string[last--]);
     }
     if(c!='')
     {
             //since we "stepped back over" the space we need to replace it
             //between words but not after the last word that ends in ''
      putchar(' ');
     }
         //we didn't change "i" itself so it still points to the space
         //now we add one to "i" to save the start position of the next word
     start = i+1;
   }
  }
return 0;
}
  1. /*
  2. I hope you mean that the code looks like gibberish and not that you ran the code and the result was gibberish. Anyway, here is the first version properly commented - the others versions are just variations on the same theme - except for java which is a horse of a different color.
  3. */
  4. #include <stdio.h>
  5. #include <string.h>
  6. int main(void)
  7. {
  8. int length,last,start = 0;
  9. char c,string[100];
  10. //prompt the user and input the string
  11. printf("Enter a string: ");
  12. gets(string);
  13. //get the string's length and add 1 for the null terminator - ''
  14. length = strlen(string)+1;
  15.     //the outer loop will "walk" over the whole string
  16.   for(int i=0; i<length; i++)
  17.   {
  18.       //extract a letter each "step"
  19.    c = string[i];
  20.      
  21.      //if the letter is a space or the null terminator start reversing
  22.    if(c == ' ' || c=='')
  23.    {
  24.          //"i" will point to the space between the words or the '' at the end
  25.          //of the sentence so go back one for the last letter of the word
  26.      last = i-1;
  27.         
  28.          //start will be 0 the first time so i-start will hold the length
  29.          //that we need to reverse and we will change start afterwards
  30.      for(int j=0; j<i-start; j++)
  31.      {
  32.              //put the letter to the output and step back one each time
  33.       putchar(string[last--]);
  34.      }
  35.      if(c!='')
  36.      {
  37.              //since we "stepped back over" the space we need to replace it
  38.              //between words but not after the last word that ends in ''
  39.       putchar(' ');
  40.      }
  41.          //we didn't change "i" itself so it still points to the space
  42.          //now we add one to "i" to save the start position of the next word
  43.      start = i+1;
  44.    }
  45.   }
  46. return 0;
  47. }
Free Programming Resources
  • wynpublishing
  • Newbie
  • Newbie
  • Avatar de Usuario
  • Registrado: Jul 02, 2003
  • Mensajes: 5
  • Status: Offline

Nota Julio 3rd, 2003, 3:33 pm

O en VBScript y #058;

Código: [ Select ]
Dim vArray
  Dim iWords
  Dim sSentence
  Dim i
  Dim x
  Dim sWord
  Dim sWordReversed
  Dim sNewSentence
  sSentence = "This is a sentence with four words"
  
  vArray = Split(sSentence, " ")
  iWords = UBound(vArray)
  For i = 0 To iWords
    sWord = vArray(i)
    Do
      sWordReversed = sWordReversed & Right(sWord, 1)
      sWord = Left(sWord, Len(sWord) - 1)
    Loop Until Len(sWord) = 0 'Loop until the length of x is zero.
    sNewSentence = sNewSentence & sWordReversed & " "
    Debug.Print vArray(i)
    Debug.Print sWordReversed
    Debug.Print sNewSentence
    sWordReversed = ""
    sWord = ""
  Next
  Erase vArray
  1. Dim vArray
  2.   Dim iWords
  3.   Dim sSentence
  4.   Dim i
  5.   Dim x
  6.   Dim sWord
  7.   Dim sWordReversed
  8.   Dim sNewSentence
  9.   sSentence = "This is a sentence with four words"
  10.   
  11.   vArray = Split(sSentence, " ")
  12.   iWords = UBound(vArray)
  13.   For i = 0 To iWords
  14.     sWord = vArray(i)
  15.     Do
  16.       sWordReversed = sWordReversed & Right(sWord, 1)
  17.       sWord = Left(sWord, Len(sWord) - 1)
  18.     Loop Until Len(sWord) = 0 'Loop until the length of x is zero.
  19.     sNewSentence = sNewSentence & sWordReversed & " "
  20.     Debug.Print vArray(i)
  21.     Debug.Print sWordReversed
  22.     Debug.Print sNewSentence
  23.     sWordReversed = ""
  24.     sWord = ""
  25.   Next
  26.   Erase vArray
  • UNFLUX
  • Genius
  • Genius
  • Avatar de Usuario
  • Registrado: Dic 20, 2002
  • Mensajes: 6382
  • Loc: twitter.com/unflux
  • Status: Offline

Nota Julio 5th, 2003, 1:49 pm

oh, para ser un codificador...* suspiro *
UNFLUX.FOTO
  • baby_eye_26
  • Born
  • Born
  • No Avatar
  • Registrado: Sep 10, 2003
  • Mensajes: 2
  • Status: Offline

Nota Septiembre 10th, 2003, 12:59 am

¿qué cambios tengo que hacer si tengo que leer de un archivo de texto que contiene líneas de texto que se va a invertir y también utilizar malloc () y free ()? También tiene que ser producto de la inversión de texto.

Por ejemplo: Buenos días!

3-2 = 1;

Después de invertir:
mañana! Bueno

1; = 3-2

¿Puede alguien ayudarme? Gracias....
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Septiembre 10th, 2003, 12:59 am

Publicar Información

  • Total de mensajes en este tema: 18 mensajes
  • Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 144 invitados
  • No puede abrir nuevos temas en este Foro
  • No puede responder a temas en este Foro
  • No puede editar sus mensajes en este Foro
  • No puede borrar sus mensajes en este Foro
  • No puede enviar adjuntos en este Foro
 
 

© 2011 Unmelted, LLC. Ozzu® es una marca registrada de Unmelted, LLC