C equivalent to BASIC Mid(), Left(), Right()?

18 Aug 2012

Ok, so I never really left BASIC behind me. VB6 is my main tool for whipping something up in a hurry. I'm slowly getting the hang of C/C++ but every now and then I can't figure out how to do very common stuff.

Like Mid(string,start,length)

Is there an available function for this?

18 Aug 2012

Below is an example of what you are looking for.

(I'm giving you the fish, please watch what I do and learn to fish... ;)

You need to look at the standart C library strxxx functions, and you need to learn about C strings, and pointers to be effective with them!

Done wrong, which is easy, they can bite you really hard when you least expect it.

Good luck.

#include "mbed.h"

#ifndef min
#define min(a,b) ( (a) < (b) ? (a) : (b) )
#endif

void mid(const char *src, size_t start, size_t length, char *dst, size_t dstlen)
{       size_t len = min( dstlen - 1, length);

        strncpy(dst, src + start, len);
        // zero terminate because strncpy() didn't ? 
        if(len < length)
                dst[dstlen-1] = 0;
}

int main()
{
        const char *stringSrc = "Hello World";
        char stringDst[9];

        // copy "World" to destination 
        mid( stringSrc, 6, strlen(stringSrc) - 6, stringDst, sizeof(stringDst));

        // show what we did
        printf( "src ...%s...\r\ndst ...%s...\r\n", stringSrc, stringDst);

        return 0;
}
19 Aug 2012

Thanks Neal, that pretty much look like what I need.

Cheers!