C :: Aufgabe #48
4 Lösungen
Testfunktion für Palindrome
Anfänger - C
von devnull
- 20.04.2014 um 17:57 Uhr
Schreibe eine Funktion isPalindrom, die für eine übergebene Zeichenkette (Wort) feststellt, ob es sich um ein Palindrom handelt (boolscher Rückgabewert).
Konsolenausgabe:
$ ./palindrom
Ein Wort eingeben: Otto
Otto ist ein Palindrom
Lösungen:
/* palindrom_1.c Vergleich String/Reverse-String
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/* string to lower case */
char *strlower(char *s) {
char *p;
for (p=s; *p; p++)
*p = tolower(*p);
return s;
}
/* reverse string */
char* strrev(char *s) {
char *pl, *pr;
char c;
for (pl=s, pr=s+strlen(s)-1; pr > pl; pl++,pr--) {
// vertausche rechts/links
c = *pl;
*pl = *pr;
*pr = c;
}
return s;
}
_Bool isPalindrom(char *s) {
char *sl = strlower(strdup(s));
return (strcmp(sl, strrev(strdup(sl))) == 0);
}
int main() {
char word[100];
printf("Ein Wort eingeben: ");
scanf("%s", word);
printf("%s ist %s Palindrom\n", word, isPalindrom(word)?"ein":"kein");
return 0;
}
/* palindrom_2.c char-Vergleich
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
_Bool isPalindrom(char *s) {
char *left = s;
char *right = s + strlen(s)-1;
for (; right > left; left++, right--)
if (tolower(*left) != tolower(*right))
return 0;
return 1;
}
int main() {
char word[100];
printf("Ein Wort eingeben: ");
scanf("%s", word);
printf("%s ist %s Palindrom\n", word, isPalindrom(word)?"ein":"kein");
return 0;
}
/* palindrom_3.c char-Vergleich,rekursiv
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define tl(x) tolower(x)
_Bool cmplr(char *l, char *r) {
if (r > l)
return (tl(*l) == tl(*r)) ? cmplr(l+1, r-1) : 0;
return 1;
}
_Bool isPalindrom(char *s) {
return cmplr(s, s + strlen(s)-1);
}
int main() {
char word[100];
printf("Ein Wort eingeben: ");
scanf("%s", word);
printf("%s ist %s Palindrom\n", word, isPalindrom(word)?"ein":"kein");
return 0;
}
#include <stdio.h>
#include <stdbool.h>
bool isPalindrom(char wort[])
{
bool auswertung;
int i, laenge;
//Initialisierung
auswertung = true;
i=0;
laenge = 0;
//Länge des Wortes
while (wort[i]!='\0') {
laenge++;
i++;
}
laenge = laenge - 1;
//Prüfen auf Palindrom
for (i=0;i<laenge;i++) {
if (wort[i] != wort[laenge - 1 - i]){
auswertung = false;
break;
}
}
return auswertung;
}
int main()
{
char wort[100];
printf("Bitte gebe ein Wort ein, ohne Großschreibung: ");
fgets(wort, 100, stdin);
if (isPalindrom(wort)==true)
printf("Es ist ein Palindrom\n");
else
printf("Es ist kein Palindrom\n");
}
