9 - Textové řetězce
Procvičovaná témata
Teoretická příprava
Délka textového řetězce:
strlen
size_t strlen(const char *str)
int strcmp(const char *str1, const char *str2)
int strncmp(const char *str1, const char *str2, size_t n)
Úkoly
Definujte textový řetězec “Everybody likes PRPA” a vypište ho. Následně vypište z tohoto řetězce pouze “likes PRP” a nakonec řetězec změňte na “Tom likes PRPA” a vypište ho. Přemýšlejte, jak to provést nejúsporněji.
Naprogramujte funkce strlen, strcmp a strncmp.
cat
echo "Hello world" | cat
Hello world
echo "Hello world" | cat2
world
echo "Hello world and hello again " | words
Hello
world
and
hello
again
echo "Hello world and hello again " | words-len
Hello 5
world 5
and 3 <--
hello 5
again 5
echo "Hello world and hello again " | words | cap
hELLO
WORLD
AND
HELLO
AGAIN
echo "Hello world" | cap
hELLO WORLD
tr
echo "Hello world" | tr 'Hl' 'Xk'
Xekko workd
echo "Hello world" | tr 'dweji' '01234'
H2llo 1orl0
Ukázkové příklady
1. příklad
#include <stdio.h>
#include <string.h>
int main()
{
char a[] = "ahoj";
// 'a', 'h', 'o', 'j', '\0'
// 0x61, 0x68, ...
printf("%s\n", a);
printf("delka retezce: sizeof %lu, strlen %lu\n", sizeof(a), strlen(a));
int I = strlen(a);
for (int i = 0; i < I; i++)
printf("%c (%x) ", a[i], a[i]);
printf("\n");
char b[] = "Everybody likes PRP!";
int tiskni = 0, mezera = 0;
I = strlen(b);
for (int i = 0; i < I; i++)
{
if (b[i] == ' ' && tiskni == 0)
{
tiskni = 1;
mezera = i + 1;
break;
}
if (tiskni == 1)
printf("%c", b[i]);
}
printf("\n");
printf("%s\n", b+10);
return 0;
}
2. příklad
#include <stdio.h>
int mystrcmp(char *a, char *b)
{
//
int i = 0;
while (*(a+i) != '\0' || b[i] != '\0')
{
if (a[i] != *(b+i)) return 1;
i++;
}
return 0;
}
int main()
{
char text1[] = "Ahoj svete";
char text2[] = "Ahoj svete";
printf("Retezce %s stejne.\n", (mystrcmp(text1, text2))?"nejsou":"jsou");
return 0;
}
Řešené příklady