Funkce substr() která je běžná v kdejakém skriptovacím jazyce (nebo modernějších jazycích jako C#, C++, ..) v jazyce C chybí. Napíšeme si tedy vlastní.
Prototyp funkce vypadá následovně:
char *substr(const char *str, int start, int length = -1)
const char *str – vstupní řetězec
int start - počáteční pozice požadovaného podřetězce
int length – délka podřetězce (nepovinné). Pokud není zadáno vrátí se zbytek řetězce od pozice start
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *substr(const char *str, int start, int length = -1)
{
unsigned int slen = strlen(str);
if (((unsigned int)start + length) > slen) return NULL;
unsigned int size = (length == -1) ? (slen - start) : length;
char *buf = (char *)malloc((size+1) * sizeof(char));
strncpy(buf, str+start, size);
buf[size] = '\0';
return buf;
}
int main()
{
char *substring;
char str[] = "Hello my big world";
if ((substring = substr(str, 9, 3)) != NULL)
{
printf("%s", substring); // vypise: "big"
free(substring);
}
return 0;
}
Jelikož funkce substr() alokuje pamět neměli bychom zapomínat ji také ručně uvolnit.
Pingback: Alexander6
Pingback: Alexander7
Pingback: DUSTIN
Pingback: PERRY
Pingback: CHARLIE
Pingback: WALLACE
Pingback: BRANDON
Pingback: ENRIQUE
Pingback: LEWIS
Pingback: TERRENCE
Pingback: EDUARDO
Pingback: TRACY
Pingback: FELIX
Pingback: JACK
Pingback: CARL
Pingback: BILLY
Pingback: BYRON
Pingback: RODNEY
Pingback: RAY
Pingback: BRANDON
Pingback: DARYL
Pingback: ALEJANDRO
Pingback: CLIFTON
Pingback: VICTOR
Pingback: TIM
Pingback: JERRY
Pingback: LEWIS
Pingback: BRETT
Pingback: BRUCE
Pingback: MARION
Pingback: JASON
Pingback: CARLOS
Pingback: RAUL
Pingback: MARVIN
Pingback: HARVEY
Pingback: BILLY
Pingback: SHANE
Pingback: ALBERTO