Skip to content

Instantly share code, notes, and snippets.

@satheesh-chandran
Created April 21, 2020 07:19
Show Gist options
  • Save satheesh-chandran/fe6030a68f59ed63188baf41a3a4aa17 to your computer and use it in GitHub Desktop.
Save satheesh-chandran/fe6030a68f59ed63188baf41a3a4aa17 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include "split.h"
int main(void)
{
char string[20] = "my name is satheesh";
SPLIT_RESULT splited_result = split(string, ' ');
print_split_array(splited_result);
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "split.h"
int min(int a, int b)
{
return a < b ? a : b;
}
int max(int a, int b)
{
return a > b ? a : b;
}
const char* substring(const char string[], int limit_1, int limit_2)
{
int low = min(limit_1, limit_2);
int high = min(max(limit_1, limit_2), strlen(string));
char *result = malloc(high - low);
int char_position = 0;
for (int index = low; index < high; index++)
{
result[char_position] = string[index];
char_position++;
}
return result;
}
SPLIT_RESULT split(char string[], char limiter)
{
int length = strlen(string);
SPLIT_RESULT splited_words = {0, malloc(length)};
string[length] = limiter;
int break_point = 0, words_count = 0;
for (int index = 0; index < length + 1; index++)
{
if (string[index] == limiter)
{
splited_words.words[words_count] = substring(string, break_point, index);
break_point = index + 1;
words_count++;
splited_words.length++;
}
}
return splited_words;
}
void print_split_array(SPLIT_RESULT splited_result)
{
for (int index = 0; index < splited_result.length; index++)
{
printf("%s\n", splited_result.words[index]);
}
}
typedef struct {
int length;
const char** words;
} SPLIT_RESULT;
int min(int, int);
int max(int, int);
const char* substring(const char string[], int, int);
SPLIT_RESULT split(char string[], char);
void print_split_array(SPLIT_RESULT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment