T
T
Tolik2014-07-08 17:21:25
C++ / C#
Tolik, 2014-07-08 17:21:25

How to split a string into pieces of a specified length in C?

There is a certain string (more precisely, an array of characters) and I want to split it into several even pieces (get an array of character arrays). True, the latter may be shorter. How to do it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
jcmvbkbc, 2014-07-08
@Diel

It depends on how you want to get the result, and what you mean by "split".
Here's an example for you:

#include <stdio.h>
int main()
{
    char string[] = "123456789";
    char (*r)[3] = (char (*)[3])string;

    printf("%c%c%c", r[1][0], r[1][1], r[1][2]);
    return 0;
}

Refine your question.

D
DancingOnWater, 2014-07-08
@DancingOnWater

Nafig array of arrays, just make an array of pointers and you will be happy.

I
Ilya Evseev, 2014-07-09
@IlyaEvseev

Not tested!

/* Declare */
char s[] = "qwerrtrhfdbsgfvasdg";
const int fraglen = 3;

/* Parse */
int slen = strlen(s);
int nfrags = (slen + fraglen - 1 ) /  fraglen;
char *p[] = malloc(nfrags * sizeof(char*));
int i;
for (i = 0; i < nfrags; i++)
        p[i] = strndup(&s[i * fraglen], fraglen);

/* Print */
for (i = 0; i < nfrags; i++)
        printf("%d = \"%s\"\n", i, p[i]);

/* Done */
for (i = 0; i < nfrags; i++)
        free(p[i]);
free(p);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question