Сначала файл заголовка, который объявляет функцию split_string
.(Поскольку вы новичок в программировании, я поместил подробные комментарии):
/* Always begin a header file with the "Include guard" so that
multiple inclusions of the same header file by different source files
will not cause "duplicate definition" errors at compile time. */
#ifndef _SPLIT_STRING_H_
#define _SPLIT_STRING_H_
/* Prints the string `s` on two lines by inserting the newline at `split_at`.
void split_string (const char* s, int split_at);
#endif
В следующем C-файле используется split_string
:
// test.c
#include <stdio.h>
#include <string.h> /* for strlen */
#include <stdlib.h> /* for atoi */
#include "split_string.h"
int main (int argc, char** argv)
{
/* Pass the first and second commandline arguments to
split_string. Note that the second argument is converted to an
int by passing it to atoi. */
split_string (argv[1], atoi (argv[2]));
return 0;
}
void split_string (const char* s, int split_at)
{
size_t i;
int j = 0;
size_t len = strlen (s);
for (i = 0; i < len; ++i)
{
/* If j has reached split_at, print a newline, i.e split the string.
Otherwise increment j, only if it is >= 0. Thus we can make sure
that the newline printed only once by setting j to -1. */
if (j >= split_at)
{
printf ("\n");
j = -1;
}
else
{
if (j >= 0)
++j;
}
printf ("%c", s[i]);
}
}
Вы можете скомпилировать и запустить программукак (при условии, что вы используете компилятор GNU C):
$ gcc -o test test.c
$ ./test "hello world" 5
hello
world