|
|||||||
|
|
|
![]() |
|
|
Strumenti |
|
|
#1 |
|
Senior Member
Iscritto dal: Jul 2003
Città: Alessandria
Messaggi: 10167
|
[C] Parole palindrome
Devo fare un programma che, presa in input una stringa di testo, è in grado di riconoscere quante delle parole inserite sono palindrome e le stampa a schermo.
Sono riuscito ad usare con successo la funzione fgets, infatti riesco a determinare la lunghezza totale, però non riesco a caricare in un altro vettore le singole parole... Questo è quello che ho scritto fino ad ora: Codice:
#include <stdio.h>
#include <string.h>
#define MAX 132
char is_palindrome (char str_text[], int len);
int string_lenght ( char str_text[], char text[] );
int main()
{
char str_text[MAX], s, text[MAX];
int len;
int i;
len = string_lenght(str_text, text);
if ( len == -1 )
{
printf("Error in reading the text\n");
return -1;
}
for (i=0; i <= len; i++)
{
s = is_palindrome(str_text, len);
}
if(s==-1)
printf("The word is a palindrome\n");
else
printf("The word is not a palindrome\n");
}
char is_palindrome (char s[], int len)
{
int i, j=len-1, k=0;
for( i=0; i<(len+1)/2; i++, j-- )
{
if(s[i]==s[j])
k++;
}
if( (k==len/2) && (len%2==0) || ( k==(len/2)+1 ) && (len%2==1) )
return 1;
else
return 0;
}
int string_lenght ( char str_text[], char text[] ) //Compute and print word lenght
{
int i, j;
int m_str_len = MAX-1;//Maximum string lenght
printf("Insert a line of text: ");
if ( (fgets(str_text, m_str_len, stdin)) == NULL )
return -1;
else
{
for(i=0; i<MAX && str_text[i]!='\0' && str_text[i] != '\n' || str_text[i] == ' '; i++)
text[i];
printf("Lenght is %d\n", i);
return i;
}
}
__________________
Dell XPS 13 (9350) :: i5-2500K - HD6870 - AsRock Z68 Pro3 - Corsair Vengeance 8GB (4x2) DDR3 :: Samsung Galaxy S4 GT-i9505
|
|
|
|
|
|
#2 |
|
Member
Iscritto dal: Aug 2005
Messaggi: 168
|
Quello che hai fatto finora funziona se passi come testo una singola parola no?
Ora ti basta modificare il main in modo che alla funzione is_palindrome (che io avrei chiamato isPalindrome Non hai bisogno di mettere le parole in un altro vettore, puoi semplicemente ciclare finchè non incontri uno spazio e quando lo trovi chiami la funzione passando str_text+inizioParola e i-inizioParola. Dovrebbe bastare questo |
|
|
|
|
|
#3 | |
|
Senior Member
Iscritto dal: Jul 2003
Città: Alessandria
Messaggi: 10167
|
Quote:
Non mi conta la lunghezza delle singole parole... La mia idea era quella di dirgli: quando trovi uno spazio ti fermi, prendi la parola e la spari in is_palindrome... Ma non ho idea di come fare...
__________________
Dell XPS 13 (9350) :: i5-2500K - HD6870 - AsRock Z68 Pro3 - Corsair Vengeance 8GB (4x2) DDR3 :: Samsung Galaxy S4 GT-i9505
|
|
|
|
|
|
|
#4 |
|
Member
Iscritto dal: Aug 2005
Messaggi: 168
|
Al momento hai un for che cicla n volte, dove n è il numero di caratteri nel testo. Tralasciando il fatto che al momento il ciclo non serve assolutamente a nulla, tu puoi usare il ciclo per controllare ogni singolo carattere, se quel carattere è uno spazio vuol dire che è la fine di una parola e devi chiamare is palindrome altrimenti non devi passare nulla.
Combinando le due cose che ho detto dovresti riuscire a risolvere il tuo problema ^^ |
|
|
|
|
|
#5 |
|
Senior Member
Iscritto dal: Jul 2003
Città: Alessandria
Messaggi: 10167
|
Ci sono quasi.
Ora succede che tutte le parole dalla prima alla penultima vengono processate correttamente. Il problema sta nell'ultima parola, infatti il ciclo for vede il null char '\0' lo legge e stoppa il ciclo ( a dir la verità non ho capito se vede il null char o il new line, cmq poco cambia ), impedendomi di prendere l'ultima parola. Questo è il codice scritto: Codice:
/*
Using the function developed in the previous exercise, write a C program that reads a line of text
from keyboard and then writes all the words in the line that are palindromes. If no word is a
palindrome, the program should print the message 'No word is a palindrome'. The program should
work with lines of up to 132 characters, ignoring characters in excess.
Hint: in order to read all the words included in a text line you can first read the whole line in a string
(using fgets) and then use the sscanf function with the %s descriptor in order to separate the words in
the line.
*/
#include <stdio.h>
#include <string.h>
#define MAX 132
int is_palindrome (int len, char str_text[len]);
int string_lenght ( char str_text[]);
int main()
{
char str_text[MAX];
int len;
len = string_lenght(str_text);
if ( len == -1 )
{
printf("Error in reading the text\n");
return -1;
}
}
int is_palindrome (int len, char str_text[len])
{
int i, j=len-1, k=0;
for( i=0; i<(len+1)/2; i++, j-- )
{
if(str_text[i]==str_text[j])
k++;
}
printf("Word: ");
if( (k==len/2) && (len%2==0) || ( k==(len/2)+1 ) && (len%2==1) )
{
for (i=0; i <len; i++)
printf("%c", str_text[i]);
printf("\nThis word is palindrome\n");
return 1;
}
else
{
for (i = 0; i <len; i++)
printf("%c", str_text[i]);
printf("\nThis word is not a palindrome\n");
return 0;
}
}
int string_lenght ( char str_text[]) //Compute and print word lenght
{
int i, j;
int k=0; // Index to store the position reached in the array
int m_str_len = MAX-1; //Maximum string lenght
char text[MAX];
printf("Insert a line of text: ");
if ( (fgets(str_text, m_str_len, stdin)) == NULL )
return -1;
else
{
for(i=0; i<MAX && str_text[i]!='\0' && str_text[i] != '\n'; i++)
{
if ( str_text[i] == ' ' || str_text[i] == '\0')
{
for ( j = 0; str_text[k+j] != ' '; j++)
{
text[j] = str_text[j+k]; //We store in text just the word that has not been processed, not the whole string
}
is_palindrome(j, text);
k += j+1; //We skip the space and go to the next char of the word
}
}
}
return 0;
}
__________________
Dell XPS 13 (9350) :: i5-2500K - HD6870 - AsRock Z68 Pro3 - Corsair Vengeance 8GB (4x2) DDR3 :: Samsung Galaxy S4 GT-i9505
|
|
|
|
|
|
#6 |
|
Junior Member
Iscritto dal: Jun 2010
Messaggi: 1
|
[C] Tutta Ricorsiva http://www.hwupgrade.it/forum/images_hwu/smilies/icon_smile.gif
#include <stdio.h>
#include <windows.h> void palindroma(char *,int,int,int*); main () { char stringa[40]; int i,j=0,grado=0,dim; printf ("Inserire stringa"); for (i=0,dim=0;(stringa[i]=getchar())!='\n';i++,dim++); palindroma(stringa,j,dim,&grado); printf ("Grado: %d",grado); system ("pause"); } void palindroma(char *p,int i,int dim,int *grado) { if (dim>0) { if (p[i]==p[dim-1]) { printf ("%c %c\n",p[i],p[dim-1]); (*grado)++; palindroma(p,++i,--dim,grado } else printf ("NON PALINDROMA"); } } |
|
|
|
|
|
#7 |
|
Senior Member
Iscritto dal: Jul 2003
Città: Alessandria
Messaggi: 10167
|
La mia intenzione non era quella di riuscire in un modo o nell'altro ad avere il programma funzionante. So anche io che sulla rete ci sono milioni di sorgenti scritti per questa compito.
Io voglio riuscirci col codice scritto da me, non serve a niente prendere quelli della rete, copiarli, compilarli e constatare che funzionano... Non si impara niente Sono qui per chiedere suggerimenti, non risoluzioni del problema.
__________________
Dell XPS 13 (9350) :: i5-2500K - HD6870 - AsRock Z68 Pro3 - Corsair Vengeance 8GB (4x2) DDR3 :: Samsung Galaxy S4 GT-i9505
|
|
|
|
|
|
#8 |
|
Senior Member
Iscritto dal: Nov 2005
Messaggi: 2780
|
Io trasformerei il tuo for in un while:
Codice:
i=0;
while(1)
{
if ( str_text[i] == ' ' || str_text[i] == '\0' || str_text[i] == '\n')
{
for ( j = 0; str_text[k+j] != ' ' && str_text[k+j] != '\0' && str_text[k+j] != '\n'; j++)
{
text[j] = str_text[j+k]; //We store in text just the word that has not been processed, not the whole string
}
is_palindrome(j, text);
k += j+1; //We skip the space and go to the next char of the word
}
if (str_text[i] == '\0' || str_text[i] == '\n')
break;
i++;
}
Se non vuoi leggere il codice (che comunque non ho provato, quindi non sono sicuro funzioni) ti spiego quello che ho fatto: Invece di usare un ciclo for ho utilizzato un ciclo while con condizione di terminazione 1, cioè non esce mai. Quando effettivamente voglio uscire uso un if (e quindi controllo se sono arrivato in fondo alla stringa) e un break, ma faccio questo controllo solo dopo aver processato la parola corrente (quindi l'ultima parola non viene saltata). In effetti avrei potuto usare un do-while... Ti ho poi aggiunto alcune condizioni che mi sembrava mancassero nell'if e nel for interni. Ad ogni modo rivedrei la struttura del programma scomponendolo in funzioni meno specializzate (nel tuo programma string_lenght fa troppe cose). |
|
|
|
|
|
#9 |
|
Senior Member
Iscritto dal: Jul 2003
Città: Alessandria
Messaggi: 10167
|
Ti ringrazio! Con questo suggerimento sono riuscito a completare il programma, che ora funziona perfettamente.
Sul fatto che string_lenght sia troppo lungo me ne sono reso conto, ma avevo intenzione di cambiare le cose solo completato il programma, visto che è il problema minore. Mi rivedrete a breve con nuovi programmi
__________________
Dell XPS 13 (9350) :: i5-2500K - HD6870 - AsRock Z68 Pro3 - Corsair Vengeance 8GB (4x2) DDR3 :: Samsung Galaxy S4 GT-i9505
|
|
|
|
|
| Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 16:02.




















