0 Franz Schmidt · May 1, 2015
Is there a function to get a substring from a certain place in a char array with a certain length?
i know there is the function strncpy or memcpy but this functions only do a substring from first letter to another letter.

Greetings Franz

Post a Reply


Oldest  Newest  Rating
0 c student · May 2, 2015
Functions which require a char *ptr parameter means a pointer to a character, not necessarily the beginning of an array.  You can manipulate the position of the pointer within an array and start from there, then limit the number of characters you want to access.  Here is an example:

#include <stdio.h>
#include <string.h>
#include <assert.h> /* Raising awareness for this guy */
#define MAX_LENGTH 256
#define length 8
int main(void) {
    char *str1 = "This is a string";
    char str2[MAX_LENGTH];
    memset (str2, 0, sizeof (str2));
    strncpy (str2, str1+5, length);
    assert (strncmp (str2, "is a str", length) == 0);
    puts (str2);
    return 0;
0 Dol Lod · May 1, 2015
So, let me test my understanding. You want a function that copies a substring from a starting character to an ending character.

char* substring(char* haystack,char start, char end);

Those are the parameters you would take in this function?

I don't think such a function exists, but you could easily make one. 
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator