Created
September 15, 2012 17:41
-
-
Save Ninputer/3729000 to your computer and use it in GitHub Desktop.
split by blank implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "stdafx.h" | |
#include <string.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
//return value: the pointer used to free the allocated buffer | |
char* split_by_blank(char * input, char **& output, size_t& item_count, size_t max_item_count) | |
{ | |
if (max_item_count <= 0) | |
{ | |
return NULL; | |
} | |
if (!input) | |
{ | |
return NULL; | |
} | |
size_t length = strlen(input); | |
char* buffer = (char*)malloc(length + 1); | |
memcpy(buffer, input, length + 1); | |
output = (char**)malloc(max_item_count * sizeof(char**)); | |
int last_is_space = 0; | |
char* last_pointer = buffer; | |
size_t item_index = 0; | |
for (size_t i = 0; i < length + 1; ++i) | |
{ | |
if (input[i] == ' ') | |
{ | |
buffer[i] = '\0'; | |
last_is_space = 1; | |
} | |
else | |
{ | |
if (last_is_space || i == length) | |
{ | |
if (item_index >= max_item_count) | |
{ | |
break; | |
} | |
if (*last_pointer != '\0') | |
{ | |
output[item_index++] = last_pointer; | |
} | |
last_pointer = &buffer[i]; | |
} | |
last_is_space = 0; | |
} | |
} | |
item_count = item_index; | |
return buffer; | |
} | |
int _tmain(int argc, _TCHAR* argv[]) | |
{ | |
using namespace std; | |
char **output; | |
size_t count; | |
char* buffer = split_by_blank(" apple banana orange peach pear", output, count, 5); | |
if (buffer) | |
{ | |
for (int i = 0; i < count; i++) | |
{ | |
printf("%s\r\n", output[i]); | |
} | |
free(buffer); | |
free(output); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment