Untitled
By: a guest | Mar 21st, 2010 | Syntax:
C | Size: 1.56 KB | Hits: 66 | Expires: Never
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "string2.h"
void strip(char* str, char car)
{
int offset = 0, i = 0;
//On enlève les espaces au début
while(str[offset++] == car);
while((str[i++] = str[offset + i - 1]) != '\0');
i--;
//Et à la fin
while(str[--i] == car);
str[i+1] = '\0';
}
char** split(const char* str, char delim, int* cnt)
{
char** stock = NULL;
int i = 0, j = 0, length = -1, debut = 0, count = 0;
// Compte le nombre de champs
while(str[i] != '\0') {
length++;
if(str[i] == delim) {
if(length)count++;
length = -1;
}
i++;
}
if(length > -1) count++;
//Réserve l'espace nécessaire
if((stock = (char**)calloc(count, sizeof(char*))) == NULL) {
*cnt = 0;
return NULL;
}
i = 0; length = -1;
//Stocke les sous-chaines
while(str[i] != '\0') {
length++;
if(str[i] == delim) {
if(length) {
if((stock[j] = (char*)calloc(length+1, sizeof(char))) == NULL) {
free_split(stock, j-1);
*cnt = 0;
return NULL;
}
strncpy(stock[j], str+debut, length);
stock[j][length] = '\0';
j++;
}
length = -1; debut = i+1;
}
i++;
}
length++;
if(length) {
if((stock[j] = (char*)calloc(length+1, sizeof(char))) == NULL) {
free_split(stock, j-1);
*cnt = 0;
return NULL;
}
strncpy(stock[j], str+debut, length);
stock[j][length] = '\0';
}
*cnt = count;
return stock;
}
void free_split(char** str, int cnt)
{
int i;
for(i = 0; i < cnt; i++)
free(str[i]);
free(str);
}