Logo

Programming-Idioms

  • C
  • Perl

Idiom #38 Extract a substring

Find substring t consisting in characters i (included) to j (excluded) of string s.
Character indices start at 0 unless specified otherwise.
Make sure that multibyte characters are properly handled.

my $chunk = substr("now is the time", $i, $j);

Perl is 0-based: i=3 would start at the 4th character.
#include <stdlib.h>
#include <string.h>
char *t=malloc((j-i+1)*sizeof(char));
strncpy(t,s+i,j-i);
T : String := S (I .. J - 1);

In Ada, strings use 1-based indexing

In Ada, J is included by default when slicing

New implementation...