Answer the question
In order to leave comments, you need to log in
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
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;
}
Nafig array of arrays, just make an array of pointers and you will be happy.
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 questionAsk a Question
731 491 924 answers to any question