C is not always faster than C++ but @Fomalhaut was right to post the performant core solution in C. Here is my (C program) complete version, based on his algorithm. Without using strncpy, too.
Here it is on the godbolt.
#ifdef __STDC_ALLOC_LIB__
#define __STDC_WANT_LIB_EXT2__ 1
#else
#define _POSIX_C_SOURCE 200809L
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include <malloc.h>
//////////////////////////////////////////////////////////////
// array of buffers == a_of_b
typedef struct a_of_b {
const unsigned size;
unsigned count ;
char ** data ;
} a_of_b ;
a_of_b a_of_b_make ( const unsigned size_ )
{
return (a_of_b){ .size = size_, .count = 0, .data = calloc(1, sizeof(char * [size_] ) ) } ;
}
a_of_b * a_of_b_append ( a_of_b * self, const unsigned len_, const char str_[len_] )
{
assert( self->data ) ;
assert( self->size > self->count ) ;
self->data[ self->count ] = strndup( str_, len_ ) ;
self->count += 1;
return self ;
}
a_of_b * a_of_b_print ( a_of_b * self , const char * fmt_ )
{
for (unsigned j = 0; j < self->count; ++j)
printf( fmt_ , self->data[j]);
return self ;
}
a_of_b * a_of_b_free ( a_of_b * self )
{
for (unsigned j = 0; j < self->count; ++j)
free( self->data[j]) ;
free( self->data) ;
self->count = 0 ;
return self ;
}
//////////////////////////////////////////////////////////////
a_of_b breakit ( const unsigned len_, const char input_[len_], const unsigned substLength )
{
assert( len_ > 2 ) ;
assert( substLength > 0 ) ;
assert( substLength < len_ ) ;
const unsigned count_of_buffers = len_ - substLength + 1;
a_of_b rez_ = a_of_b_make( count_of_buffers +1 ) ;
for (int i = 0; i < count_of_buffers ; i++) {
a_of_b_append( &rez_, substLength, input_ + i ) ;
}
return rez_ ;
}
//////////////////////////////////////////////////////////////
static void driver( const char * input_, const unsigned substLength )
{
printf("\n");
a_of_b substrings = breakit( strlen(input_), input_, substLength );
a_of_b_print( & substrings , "%s ");
a_of_b_free( & substrings);
}
//////////////////////////////////////////////////////////////
int main () {
driver( "RADILAMIA", 4) ;
driver( "RADILAMIA", 3) ;
driver( "RADILAMIA", 2) ;
driver( "RADILAMIA", 1) ;
return EXIT_SUCCESS;
}
And the program output is:
RADI ADIL DILA ILAM LAMI AMIA
RAD ADI DIL ILA LAM AMI MIA
RA AD DI IL LA AM MI IA
R A D I L A M I A
Enjoy.