-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringVector.c
More file actions
84 lines (75 loc) · 2.09 KB
/
StringVector.c
File metadata and controls
84 lines (75 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "StringVector.h"
void
string_vector_init( struct StringVector *this, size_t capacity )
{
this->capacity = capacity;
this->size = 0;
this->strings = malloc( capacity * sizeof( char * ) );
}
void
string_vector_free( struct StringVector *this )
{
for ( int i = 0; i < (int)( this->size ); i++ ) {
free( this->strings[i] );
}
free( this->strings );
}
void
string_vector_add( struct StringVector *this, const char *begin, const char *end )
{
if ( this->capacity == this->size ) {
this->capacity *= 2;
this->strings = realloc( this->strings, this->capacity * sizeof( char * ) );
}
if ( NULL == begin )
this->strings[this->size++] = NULL;
else
this->strings[this->size++] = strndup( begin, end - begin );
}
size_t
string_vector_size( const struct StringVector *this )
{
return this->size;
}
char *
string_vector_get( const struct StringVector *this, size_t index )
{
return this->strings[index];
}
struct StringVector
split_line( char *line )
{
struct StringVector tokens;
string_vector_init( &tokens, 8 );
char *start = NULL; // where the current token starts. NULL if no token
for ( char *p = line; *p != '\0'; p++ ) {
if ( ( start == NULL ) && !isspace( *p ) ) {
// starting a new token
start = p;
}
else if ( ( start != NULL ) && isspace( *p ) ) {
string_vector_add( &tokens, start, p );
start = NULL;
};
}
return tokens;
}
char *
strjoinarray( char *dest, const struct StringVector *this, size_t fist, size_t last, char *glue )
{
size_t glue_length = strlen( glue );
char * target = dest; // where to copy the next elements
*target = '\0';
for ( size_t i = fist; i < last; i++ ) {
if ( i > 0 ) { // need glue ?
strcat( target, glue );
target += glue_length;
}
strcat( target, this->strings[i] );
target += strlen( this->strings[i] ); // move to the end
};
return dest;
}