Делим string на части - C (СИ)
Формулировка задачи:
Привет, возникла следующая проблема есть два массива number[10] и command[10], нужно их соединить вместе но чтобы между ними была точка с запятой ';', а потом нужно этот новый массив разделить на две части new_number[10] и new_command[10]. Привожу ниже свой код, буду благодарен за советы как сделать это правильнее и красивее
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char old_num[10] = "123456";
char old_com[10] = "text";
char buffer[50];
sprintf(buffer, "%s%c%s%c", old_num, ';', old_com, '\0');
char number[10];
char cmd[10];
char *p = strchr(buffer, ';');
memcpy(number, buffer, p - buffer);
number[p - buffer] = '\0';
*(p++);
char *p2 = strchr(p, '\0');
memcpy(cmd, p, p2 - p);
cmd[p2 - p] = '\0';
return 0;
}Решение задачи: «Делим string на части»
textual
Листинг программы
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char* usage = "Module for a big project usage:\n\
<program> --option [str1, [str2]]\n";
#define HELP "--help"
#define CONCAT "--concat"
#define SPLIT "--split"
#define DELIMITER ';'
void
help_usage (int need, int have) {
if (need != have) {
fprintf(stderr, "%s", usage);
exit(EXIT_FAILURE);
}
}
void
bad_alloc () {
fprintf(stderr, "bad memory allocation");
exit(EXIT_FAILURE);
}
int
main (int argc, char** argv)
{
if (strcmp(argv[1], HELP) == 0) {
fprintf(stdout, "%s", usage);
exit(EXIT_SUCCESS);
}
if (strcmp(argv[1], CONCAT) == 0) {
help_usage(4, argc);
{
char *s = NULL;
size_t len1 = strlen(argv[2]);
size_t len2 = strlen(argv[3]);
if ((s = malloc((len1 + len2 + 2) * sizeof(char))) == NULL) {
bad_alloc();
}
memmove(s, argv[2], len1);
s[len1] = DELIMITER;
memmove(&s[len1 + 1], argv[3], len2);
fprintf(stdout, "It's greet good! Result are: %s\n", s);
free(s);
exit(EXIT_SUCCESS);
}
}
if (strcmp(argv[1], SPLIT) == 0) {
help_usage(3, argc);
{
char *s1 = NULL, *s2 = NULL, *delim = NULL;
if ((delim = strchr(argv[2], (int)DELIMITER)) == NULL) {
fprintf(stdout, "No match delimiter %c in %s\n", DELIMITER, argv[2]);
exit(EXIT_SUCCESS);
} else {
size_t len = strlen(argv[2]);
if (((s1 = malloc(delim - &argv[2][0] + 1)) == NULL) ||
((s2 = malloc(&argv[2][len] - delim)) == NULL)) {
bad_alloc();
}
memmove(s1, argv[2], delim - &argv[2][0]);
s1[delim - &argv[2][0]] = '\0';
memmove(s2, delim + 1, &argv[2][len] - delim);
s2[&argv[2][len] - delim] = '\0';
fprintf(stdout, "%s\n%s\n", s1, s2);
free(s1);
free(s2);
exit(EXIT_SUCCESS);
}
}
}
exit(EXIT_FAILURE);
}