src/ucx/string.c

changeset 135
471e28cca288
parent 99
b9a6af0ae41a
child 254
4784c14aa639
equal deleted inserted replaced
134:44415e4399ce 135:471e28cca288
1 /* 1 /*
2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. 2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3 * 3 *
4 * Copyright 2015 Olaf Wintermann. All rights reserved. 4 * Copyright 2016 Olaf Wintermann. All rights reserved.
5 * 5 *
6 * Redistribution and use in source and binary forms, with or without 6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met: 7 * modification, are permitted provided that the following conditions are met:
8 * 8 *
9 * 1. Redistributions of source code must retain the above copyright 9 * 1. Redistributions of source code must retain the above copyright
173 n.ptr = NULL; 173 n.ptr = NULL;
174 n.length = 0; 174 n.length = 0;
175 return n; 175 return n;
176 } 176 }
177 177
178 sstr_t sstrstr(sstr_t string, sstr_t match) {
179 if (match.length == 0) {
180 return string;
181 }
182
183 for (size_t i = 0 ; i < string.length ; i++) {
184 sstr_t substr = sstrsubs(string, i);
185 if (sstrprefix(substr, match)) {
186 return substr;
187 }
188 }
189
190 sstr_t emptystr;
191 emptystr.length = 0;
192 emptystr.ptr = NULL;
193 return emptystr;
194 }
195
178 sstr_t* sstrsplit(sstr_t s, sstr_t d, ssize_t *n) { 196 sstr_t* sstrsplit(sstr_t s, sstr_t d, ssize_t *n) {
179 return sstrsplit_a(ucx_default_allocator(), s, d, n); 197 return sstrsplit_a(ucx_default_allocator(), s, d, n);
180 } 198 }
181 199
182 sstr_t* sstrsplit_a(UcxAllocator *allocator, sstr_t s, sstr_t d, ssize_t *n) { 200 sstr_t* sstrsplit_a(UcxAllocator *allocator, sstr_t s, sstr_t d, ssize_t *n) {
199 *n = -2; 217 *n = -2;
200 return NULL; 218 return NULL;
201 } 219 }
202 220
203 for (size_t i = 0 ; i < s.length ; i++) { 221 for (size_t i = 0 ; i < s.length ; i++) {
204 if (sv.ptr[i] == d.ptr[0]) { 222 sstr_t substr = sstrsubs(sv, i);
205 _Bool match = 1; 223 if (sstrprefix(substr, d)) {
206 for (size_t j = 1 ; j < d.length ; j++) { 224 (*n)++;
207 if (j+i < s.length) { 225 for (size_t j = 0 ; j < d.length ; j++) {
208 match &= (sv.ptr[i+j] == d.ptr[j]); 226 sv.ptr[i+j] = 0;
209 } else {
210 match = 0;
211 break;
212 }
213 } 227 }
214 if (match) { 228 i += d.length - 1; // -1, because the loop will do a i++
215 (*n)++;
216 for (size_t j = 0 ; j < d.length ; j++) {
217 sv.ptr[i+j] = 0;
218 }
219 i += d.length;
220 }
221 } 229 }
222 if ((*n) == nmax) break; 230 if ((*n) == nmax) break;
223 } 231 }
224 result = (sstr_t*) almalloc(allocator, sizeof(sstr_t)*(*n)); 232 result = (sstr_t*) almalloc(allocator, sizeof(sstr_t)*(*n));
225 233

mercurial