forked from RoboCore/String_Functions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
String_Functions.cpp
802 lines (648 loc) · 22.4 KB
/
String_Functions.cpp
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
/*
RoboCore String Functions Library
(v1.5 - 17/12/2015)
Library to manipulate strings
(tested with Arduino 0022 and 1.0.1)
Copyright 2013 RoboCore (François) ( http://www.RoboCore.net )
------------------------------------------------------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------------
NOTE: the library uses malloc() to create the strings and
the Pointer List in <Memory.h> is usedby default .
To use regular malloc(), undefine USE_POINTER_LIST
in <Memory.h>
NOTE: more functions (and alternative ones) can be found
in the <string.h> library
NOTE: SoftwareSerial is only available for Arduino 1.0.1+
OBS: char* str1 = "test";
//in .DATA section, DO NOT free (because will
add this address to the free_list)
char* str2 = (char*)malloc(10);
//in the HEAP, so CAN be freed
*/
#include "String_Functions.h"
unsigned int RC_READ_SERIAL_DELAY = 10000; //in [us]
//-------------------------------------------------------------------------------------------------
// Convert an integer (long) to a string
// NOTE: it is recommended to create the buffer of at least 6 characters because
// the code adds the NULL termination
// NOTE: the buffer must be at least 2 characters long
void IntToStr(long value, char *buffer, int buffer_size){
// check for a valid buffer
if(buffer_size < 2)
return;
buffer_size--; // update, because array is 0 based (buffer_size is passed by value)
// check for simples and common value
if(value == 0){
buffer[0] = 48; // '0' in ASCII char
buffer[1] = '\0';
return;
}
byte negative = 0;
if(value < 0){
negative = 1;
value *= -1;
}
buffer[buffer_size] = '\0'; // EOS in the last position
// parse the value (value is passed by value)
for(int i=1 ; i <= buffer_size ; i++){
if(value == 0){
if(negative != 0){
buffer[buffer_size-i] = '-'; // add negative sign
negative = 0; // reset
} else {
buffer[buffer_size-i] = 48; // fill with leading zeros
}
} else {
buffer[buffer_size-i] = (value % 10) + 48; // convert to ASCII char
}
value /= 10;
}
// remove leading zeros
byte count = 0;
for(int i=0 ; i < (buffer_size - 1) ; i++){
if(buffer[i] == '0')
count++;
else
break; // can have a 0 inside the number
}
for(int i=0 ; i < (buffer_size - count) ; i++){
buffer[i] = buffer[i+count];
}
buffer[buffer_size - count] = '\0'; // EOS in the last position (there can be more characters after that)
}
//-------------------------------------------------------------------------------------------------
// Read a string from serial until buffer is full, eol is reached (if eol not NULL) or
// no more characters in the serial buffer (if eol is NULL)
// (returns the string length)
// NOTE: it is recommended to create the buffer with 1 additional char because
// the code adds the NULL termination
// (ex: desired size = 30 >> create with 31 and pass this value as parameter)
int ReadFromSerial(HardwareSerial *serial, char *buffer, int buffer_size, char eol, unsigned long timeout){
int count = 0;
if(eol == NULL){ //default value, means wait for full buffer or no more characters
while(serial->available()){
buffer[count++] = serial->read();
delayMicroseconds(RC_READ_SERIAL_DELAY); //wait for all data to arrive
//check for buffer overflow
if(count >= buffer_size){
// //flush serial buffer
// while(serial->available()){
// char c = serial->read();
// }
break; //exit main while loop
}
}
//add '\0' at the end (NULL terminated string)
buffer[buffer_size - 1] = '\0';
if(count < buffer_size)
buffer[count] = '\0';
//correction for exact buffer size
if(count == buffer_size)
count--;
return count;
} else { //wait for eol and ignore if serial buffer is empty
unsigned long start_time = millis(); //start the timer
char c = eol - 1; //assign a different value for the first time
while(c != eol){
if(serial->available()){
start_time = millis(); //reset to give time to type the entire message
c = serial->read();
buffer[count++] = c;
}
delayMicroseconds(RC_READ_SERIAL_DELAY); //wait for all data to arrive
//check for buffer overflow
if(count >= buffer_size){
// //flush serial buffer
// while(serial->available()){
// c = serial->read();
// }
break; //exit main while loop
}
//check timeout
if(millis() >= (start_time + timeout)){
if(timeout != 0){
count++; //(+1) to correct the index when nothing or no EOL received
break; //exit while loop
}
}
}
//add '\0' at the end (NULL terminated string)
buffer[buffer_size - 1] = '\0';
if(count < buffer_size)
buffer[count - 1] = '\0'; //(-1) because EOL is included
return (count - 1); //(-1) because EOL is included
}
}
//------------------------
#ifdef STRING_FUNCTIONS_SOFTWARE_SERIAL
// Read a string from serial until buffer is full, eol is reached (if eol not NULL) or
// no more characters in the serial buffer (if eol is NULL)
// (returns the string length)
// NOTE: it is recommended to create the buffer with 1 additional char because
// the code adds the NULL termination
// (ex: desired size = 30 >> create with 31 and pass this value as parameter)
int ReadFromSerial(SoftwareSerial *serial, char *buffer, int buffer_size, char eol, unsigned long timeout){
int count = 0;
if(eol == NULL){ //default value, means wait for full buffer or no more characters
while(serial->available()){
buffer[count++] = serial->read();
delayMicroseconds(RC_READ_SERIAL_DELAY); //wait for all data to arrive
//check for buffer overflow
if(count >= buffer_size){
// //flush serial buffer
// while(serial->available()){
// char c = serial->read();
// }
break; //exit main while loop
}
}
//add '\0' at the end (NULL terminated string)
buffer[buffer_size - 1] = '\0';
if(count < buffer_size)
buffer[count] = '\0';
//correction for exact buffer size
if(count == buffer_size)
count--;
return count;
} else { //wait for eol and ignore if serial buffer is empty
unsigned long start_time = millis(); //start the timer
char c = eol - 1; //assign a different value for the first time
while(c != eol){
if(serial->available()){
start_time = millis(); //reset to give time to type the entire message
c = serial->read();
buffer[count++] = c;
}
delayMicroseconds(RC_READ_SERIAL_DELAY); //wait for all data to arrive
//check for buffer overflow
if(count >= buffer_size){
// //flush serial buffer
// while(serial->available()){
// c = serial->read();
// }
break; //exit main while loop
}
//check timeout
if(millis() >= (start_time + timeout)){
if(timeout != 0){
count++; //(+1) to correct the index when nothing or no EOL received
break; //exit while loop
}
}
}
//add '\0' at the end (NULL terminated string)
buffer[buffer_size - 1] = '\0';
if(count < buffer_size)
buffer[count - 1] = '\0'; //(-1) because EOL is included
return (count - 1); //(-1) because EOL is included
}
}
#endif
//-------------------------------------------------------------------------------------------------
//IMPORTANT: DO NOT forget to cast to (byte) when calling overloads with 'option'
int StrCompare(char* str1, char* str2){
return StrCompare(str1, str2, 0, StrLength(str2), CASE_SENSITIVE);
}
int StrCompare(char* str1, char* str2, byte options){
return StrCompare(str1, str2, 0, StrLength(str2), options);
}
//-----------------------------------
int StrCompare(char* str1, char* str2, int start){
return StrCompare(str1, str2, start, StrLength(str2), CASE_SENSITIVE);
}
int StrCompare(char* str1, char* str2, int start, byte options){
return StrCompare(str1, str2, start, StrLength(str2), options);
}
//-----------------------------------
int StrCompare(char* str1, char* str2, int start, int length){
return StrCompare(str1, str2, start, length, CASE_SENSITIVE);
}
//-----------------------------------
// Compares str2 with str1 and with given options, starting from start in str1
// and until length or end of str2 is reached
// NOTE: by default start = 0, length = StrLength(str2) and is CASE_SENSITIVE
// (returns the number of matched characters (0 if none matched) or
// -1 on errror)
// NOTE: if(return == StrLength(str2)), str2 was found in str1. Otherwise
// only part (or nothing) of str2 was found
int StrCompare(char* str1, char* str2, int start, int length, byte options){
//validate input
if(start < 0)
return -1;
if(length <= 0)
return -1;
//get length of the strings
int len1 = StrLength(str1);
int len2 = StrLength(str2);
//check strings
if((len1 == 0) || (len2 == 0))
return -1;
else if(len2 > len1)
return -1;
//check total length
if(len1 < (start + len2))
return -1;
//start comparison
int match = 0;
char c1, c2;
for(int i=0 ; i < length ; i++){
//search until end of str2 or length
if(i >= len2)
break;
//get chars to compare
c1 = str1[i + start]; //get with offset
c2 = str2[i]; //get unchanged
//binary comparison
if((c1 != c2) && (options ^ CASE_INSENSITIVE)){ //different character and case SENSITIVE
break;
} else if((c1 != c2) && (options & CASE_INSENSITIVE)){ //case INSENSITIVE comparison
if((c1 >= 97) && (c1 <= 122)) //'a' to 'z'
c1 -= 32; //convert to 'A' to 'Z'
if((c2 >= 97) && (c2 <= 122)) //'a' to 'z'
c2 -= 32; //convert to 'A' to 'Z'
if(c1 != c2) //different characters
break;
}
match++; //if reached here, means characters are equal
}
return match;
}
//-------------------------------------------------------------------------------------------------
// Concatenate two strings
// NOTE: it doesn't change any of the given strings
// (returns NULL on error or if given strings are empty, pointer to one of the strings
// if the other is empty, or the concatenated string)
char* StrConcat(char* str1, char* str2){
int len1 = StrLength(str1);
int len2 = StrLength(str2);
//check strings
if((len1 == 0) && (len2 == 0))
return NULL;
else if(len1 == 0)
return str2;
else if(len2 == 0)
return str1;
//create new temporary string
#ifdef USE_POINTER_LIST
PointerList::Initialize();
char* newstr = (char*)Mmalloc((len1 + len2 + 1) * sizeof(char));
#else
char* newstr = (char*)malloc((len1 + len2 + 1) * sizeof(char));
#endif
if(newstr == NULL){
#ifdef RC_STRING_DEBUG
Serial.println("ERROR in StrConcat: cannot allocate memory!");
#endif
return NULL;
}
//fill string
newstr[len1+len2] = '\0'; //insert End Of String
for(int i=0 ; i < len1 ; i++)
newstr[i] = str1[i];
for(int i=0 ; i < len2 ; i++)
newstr[i + len1] = str2[i];
return newstr;
}
//-------------------------------------------------------------------------------------------------
// Finds the position of a character in a string
// NOTE: by default uses CASE_SENSITIVE comparison
// (returns -1 if 'string' is empty, 'c' wasn't found or 'c' is NULL)
int StrFind(char* string, char c){
return StrFind(string, c, CASE_SENSITIVE);
}
// Finds the position of a character in a string
// (returns -1 if 'string' is empty, 'c' wasn't found or 'c' is NULL)
int StrFind(char* string, char c, byte options){
int length = StrLength(string);
int pos = -1;
//check length
if(length == 0)
return pos;
if(c == NULL)
return pos;
//find character
for(int i=0 ; i < length ; i++){
//binary comparison
if(c == string[i]){
pos = i;
break;
}
//case INSENSITIVE comparison
if(options & CASE_INSENSITIVE){
if((c >= 65) && (c <= 90)){ //'A' to 'Z'
if((c + 32) == string[i]){
pos = i;
break;
}
}
if((c >= 97) && (c <= 122)){ //'a' to 'z'
if((c - 32) == string[i]){
pos = i;
break;
}
}
}
}
return pos;
}
//-----------------------------------
// Finds the position of str2 in str1
// NOTE: by default uses CASE_SENSITIVE comparison
// (returns -1 if str2 > str1, str2 is empty or coudn't find)
int StrFind(char* str1, char* str2){
return StrFind(str1, str2, CASE_SENSITIVE);
}
// Finds the position of str2 in str1
// (returns -1 if str2 > str1, str2 is empty or coudn't find)
int StrFind(char* str1, char* str2, byte options){
int len1 = StrLength(str1);
int len2 = StrLength(str2);
int pos = -1;
//check length
if(len1 < len2)
return pos;
if(len2 == 0)
return pos;
//find character
boolean began = false; //true when found the first character
char c1, c2;
for(int i=0 ; i < len1 ; i++){
//check if already found
if((pos != -1) && ((i - pos) >= len2))
break;
//get chars to compare
c1 = str1[i]; //get unchanged
if(!began) //if not yet found, compare with first
c2 = str2[0];
else //otherwise get next
c2 = str2[i - pos];
//binary comparison
if(c1 == c2){
if(!began){ //assign once
pos = i;
began = true; //set
}
} else if(began && (options ^ CASE_INSENSITIVE)){ //broke sequence and is CASE_SENSITIVE, so find next
pos = -1;
began = false; //reset
}
//case INSENSITIVE comparison
if(options & CASE_INSENSITIVE){
if((c1 >= 97) && (c1 <= 122)) //'a' to 'z'
c1 -= 32; //convert to 'A' to 'Z'
if((c2 >= 97) && (c2 <= 122)) //'a' to 'z'
c2 -= 32; //convert to 'A' to 'Z'
if(c1 == c2){
if(!began){ //assign once
pos = i;
began = true; //set
}
} else if(began){ //broke sequence (already checked for binary), so find next
pos = -1;
began = false; //reset
}
}
}
//check if valid data (could have found the last characters of the string but not all of them)
if((pos + len2 - 1) > len1)
pos = -1; //reset
return pos;
}
//-------------------------------------------------------------------------------------------------
// Get the length of a string
int StrLength(char* string){
int length = 0;
boolean leave = false;
//find the length of the string
while(!leave){
if(string[length] == '\0')
leave = true;
else
length++;
}
return length;
}
//-------------------------------------------------------------------------------------------------
// Parses the string to get the string at the desired index (1 based)
// (returns NULL if the string is empty (length of 0), if NULL delimiter or
// if the index is not valid, or the desired string)
char* StrParser(char* string, char delimiter, int index){
//NOTE: it is preferable to use the same (almost) code of StrParserLength() to avoid
// growing the stack and more processing
//check if valid length
int length = StrLength(string);
if(length <= 0) //no string
return NULL;
//check delimiter
if(delimiter == NULL)
return NULL;
//parse
int current_string = 1; //assume at least one exists, even if no delimiter was found
if(string[0] == delimiter) //oups, the string begins with a delimiter, so must reset the counter
current_string = 0;
boolean found_delimiter = false;
int string_length = 0; //the length of the desired string
int pos = -1; //the position were the desired string was found
for(int i=0 ; (i < length) && (current_string <= index) ; i++){
if(string[i] == delimiter){
found_delimiter = true; //found one!
} else if(found_delimiter){
found_delimiter = false; //reset
current_string++; //one more string!
}
//leave loop if the string was already found
if(current_string > index)
break;
//if is the desired string, add one character
if((current_string == index) && !found_delimiter)
string_length++;
//store the initial position of the desired string
if((current_string == index) && (pos == -1)) //must store only once
pos = i;
}
//check if the string was found
if(pos == -1){ // OR (string_length == 0)
return NULL;
}
//create new temporary string
#ifdef USE_POINTER_LIST
PointerList::Initialize();
char* newstr = (char*)Mmalloc((string_length + 1) * sizeof(char)); //allocate memory
#else
char* newstr = (char*)malloc((string_length + 1) * sizeof(char)); //allocate memory
#endif
if(newstr == NULL){
#ifdef RC_STRING_DEBUG
Serial.println("ERROR in StrParse: cannot allocate memory!");
#endif
return NULL;
}
//fill string
newstr[string_length] = '\0'; //insert End Of String
for(int i=0 ; i < string_length ; i++){
newstr[i] = string[pos+i];
}
return newstr;
}
//-------------------------------------------------------------------------------------------------
// Get the length of the string (of given index >> 1 based) in the string to parse
// (returns 0 if empty string, NULL delimiter or invalid index, or the string length)
int StrParserLength(char* string, char delimiter, int index){
//check if valid length
int length = StrLength(string);
if(length <= 0) //no string
return 0;
//check delimiter
if(delimiter == NULL)
return 0;
//find number of strings
int current_string = 1; //assume at least one exists, even if no delimiter was found
if(string[0] == delimiter) //oups, the string begins with a delimiter, so must reset the counter
current_string = 0;
boolean found_delimiter = false;
int string_length = 0;
for(int i=0 ; (i < length) && (current_string <= index) ; i++){
if(string[i] == delimiter){
found_delimiter = true; //found one!
} else if(found_delimiter){
found_delimiter = false; //reset
current_string++; //one more string!
}
//leave loop if the string was already found
if(current_string > index)
break;
//if is the desired string, add one character
if((current_string == index) && !found_delimiter)
string_length++;
}
return string_length;
}
//-------------------------------------------------------------------------------------------------
// Get the number of valid strings to parse
// (returns 0 if empty string or NULL delimiter, or the number of strings)
int StrParserQty(char* string, char delimiter){
//check if valid length
int length = StrLength(string);
if(length <= 0) //oups, I guess there was no string after all
return 0;
//check delimiter
if(delimiter == NULL)
return 0;
//find number of strings
int num_strings = 1; //assume at least one exists, even if no delimiter was found
if(string[0] == delimiter) //oups, the string begins with a delimiter, so must reset the counter
num_strings = 0;
boolean found_delimiter = false;
for(int i=0 ; i < length ; i++){
if(string[i] == delimiter){
found_delimiter = true; //found one!
} else if(found_delimiter){
found_delimiter = false; //reset
num_strings++; //one more string!
}
}
return num_strings;
}
//-------------------------------------------------------------------------------------------------
// Removes a character from a string
// (returns NULL on error or if 'string' is empty, pointer to 'string' if 'c' is NULL)
char* StrRemove(char* string, char c){
int length = StrLength(string);
//check length
if(length == 0)
return NULL;
if(c == NULL)
return string;
//find the number of ocurences
int count = 0;
for(int i=0 ; i < length; i++){
if(string[i] == c)
count++;
}
//allocates
#ifdef USE_POINTER_LIST
PointerList::Initialize();
char* res = (char*)Mmalloc((length - count + 1) * sizeof(char));
#else
char* res = (char*)malloc((length - count + 1) * sizeof(char));
#endif
if(res == NULL){
#ifdef RC_STRING_DEBUG
Serial.println("ERROR in StrRemove: cannot allocate memory!");
#endif
return NULL;
}
//assign values
int index = 0;
res[length - count] = '\0';
for(int i=0 ; i < length ; i++){
if(string[i] != c){
res[index] = string[i];
index++;
}
}
return res;
}
//-----------------------------------
// Removes a series of characters from a string
// (returns NULL on error or if given string is empty, pointer to 'string' if 'characters' is empty)
char* StrRemove(char* string, char* characters){
int length = StrLength(string);
int lenc = StrLength(characters);
//check length
if(length == 0)
return NULL;
if(lenc == 0)
return string;
//find the number of ocurences
int count = 0;
for(int i=0 ; i < length; i++){
for(int j=0 ; j < lenc ; j++){
if(string[i] == characters[j])
count++;
}
}
//allocates
#ifdef USE_POINTER_LIST
PointerList::Initialize();
char* res = (char*)Mmalloc((length - count + 1) * sizeof(char));
#else
char* res = (char*)malloc((length - count + 1) * sizeof(char));
#endif
if(res == NULL){
#ifdef RC_STRING_DEBUG
Serial.println("ERROR in StrRemove: cannot allocate memory!");
#endif
return NULL;
}
//assign values
int index = 0;
boolean add;
res[length - count] = '\0';
for(int i=0 ; i < length ; i++){
add = true;
//check whether to add or not
for(int j=0 ; j < lenc ; j++){
if(string[i] == characters[j]){
add = false;
break; //avoid more processing
}
}
if(add){
res[index] = string[i];
index++;
}
}
return res;
}
//-------------------------------------------------------------------------------------------------