File: stringUtils.cpp

package info (click to toggle)
between 6%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, jessie, jessie-kfreebsd, stretch
  • size: 3,532 kB
  • sloc: cpp: 28,110; php: 718; ansic: 638; objc: 245; sh: 236; makefile: 99; perl: 67
file content (450 lines) | stat: -rw-r--r-- 11,439 bytes parent folder | download | duplicates (10)
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
/*
 * Modification History
 *
 * 2003-May-10   Jason Rohrer
 * Created.
 * Added a tokenization function.
 *
 * 2003-June-14   Jason Rohrer
 * Added a join function.
 *
 * 2003-June-22   Jason Rohrer
 * Added an autoSprintf function.
 *
 * 2003-July-27  Jason Rohrer
 * Fixed bugs in autoSprintf return values for certain cases.
 *
 * 2003-August-12  Jason Rohrer
 * Added a concatonate function.
 *
 * 2003-September-7  Jason Rohrer
 * Changed so that split returns last part, even if it is empty.
 *
 * 2004-January-15  Jason Rohrer
 * Added work-around for MinGW vsnprintf bug.
 *
 * 2006-June-2  Jason Rohrer
 * Added a stringStartsWith function.
 *
 * 2009-September-7  Jason Rohrer
 * Fixed int types.
 * Switched away from StringBufferOutputStream to new function in SimpleVector.
 *
 * 2010-May-14    Jason Rohrer
 * String parameters as const to fix warnings.
 */



#include "stringUtils.h"

#include <stdarg.h>



char *stringToLowerCase( const char *inString  ) {

    unsigned int length = strlen( inString );

    char *returnString = stringDuplicate( inString );
    
    for( unsigned int i=0; i<length; i++ ) {
        returnString[i] = (char)tolower( returnString[i] );
        }

    return returnString;
    }



char *stringLocateIgnoreCase( const char *inHaystack,
                              const char *inNeedle ) {

    char *lowerHaystack = stringToLowerCase( inHaystack );
    char *lowerNeedle = stringToLowerCase( inNeedle );

    char *matchPointer = strstr( lowerHaystack, lowerNeedle );

    char *returnString = NULL;
    
    if( matchPointer != NULL ) {

        unsigned int matchRemainderLength = strlen( matchPointer );

        unsigned int haystackIndex = 
            strlen( inHaystack ) -  matchRemainderLength;
    
        returnString =  (char*)( &( inHaystack[ haystackIndex ] ) );
        }

    delete [] lowerHaystack;
    delete [] lowerNeedle;

    return returnString;
    }



int stringCompareIgnoreCase( const char *inStringA,
                             const char *inStringB ) {

    char *lowerA = stringToLowerCase( inStringA );
    char *lowerB = stringToLowerCase( inStringB );

    int returnVal = strcmp( lowerA, lowerB );

    delete [] lowerB;
    delete [] lowerA;

    return returnVal;
    }



char stringStartsWith( const char *inString, const char *inPrefix ) {
    unsigned int prefixLength = strlen( inPrefix );
    unsigned int stringLength = strlen( inString );
    
    if( prefixLength > stringLength ) {
        return false;
        }
    else {
        for( unsigned int i=0; i<prefixLength; i++ ) {
            if( inString[i] != inPrefix[i] ) {
                return false;
                }
            }

        // all characters, up to prefix length, are equal in both strings
        return true;
        }
    }



char **split( const char *inString, const char *inSeparator, 
              int *outNumParts ) {
    SimpleVector<char *> *parts = new SimpleVector<char *>();
    
    char *workingString = stringDuplicate( inString );
    char *workingStart = workingString;

    unsigned int separatorLength = strlen( inSeparator );

    char *foundSeparator = strstr( workingString, inSeparator );

    while( foundSeparator != NULL ) {
        // terminate at separator        
        foundSeparator[0] = '\0';
        parts->push_back( stringDuplicate( workingString ) );

        // skip separator
        workingString = &( foundSeparator[ separatorLength ] );
        foundSeparator = strstr( workingString, inSeparator );
        }

    // add the remaining part, even if it is the empty string
    parts->push_back( stringDuplicate( workingString ) );

                      
    delete [] workingStart;

    *outNumParts = parts->size();
    char **returnArray = parts->getElementArray();
    
    delete parts;

    return returnArray;
    }



char *join( char **inStrings, int inNumParts, const char *inGlue ) {
    SimpleVector<char> result;

    for( int i=0; i<inNumParts - 1; i++ ) {
        result.appendElementString( inStrings[i] );
        result.appendElementString( inGlue );
        }
    // no glue after last string
    result.appendElementString( inStrings[ inNumParts - 1 ] );

    char *returnString = result.getElementString();

    return returnString;
    }



char *concatonate( const char *inStringA, const char *inStringB ) {
    char **tempArray = new char*[2];
    tempArray[ 0 ] = (char *)inStringA;
    tempArray[ 1 ] = (char *)inStringB;

    char *result = join( tempArray, 2, "" );

    delete [] tempArray;

    return result;
    }
    


char *replaceOnce( const char *inHaystack, const char *inTarget,
                   const char *inSubstitute,
                   char *outFound ) {
    
    char *haystackCopy = stringDuplicate( inHaystack );
    
	char *fieldTargetPointer = strstr( haystackCopy, inTarget );


    if( fieldTargetPointer == NULL ) {
        // target not found
        *outFound = false;
        return haystackCopy;
        }
    else {
        // target found

		// prematurely terminate haystack copy string at
        // start of target occurence
        // (okay, since we're working with a copy of the haystack argument)
		fieldTargetPointer[0] = '\0';

		// pointer to first char after target occurrence
		char *fieldPostTargetPointer =
            &( fieldTargetPointer[ strlen( inTarget ) ] );

        char *returnString = new char[
            strlen( inHaystack )
            - strlen( inTarget )
            + strlen( inSubstitute ) + 1 ];
        
		sprintf( returnString, "%s%s%s",
				 haystackCopy,
				 inSubstitute,
				 fieldPostTargetPointer );

		delete [] haystackCopy;

        *outFound = true;
        return returnString;
		}
    
    }



char *replaceAll( const char *inHaystack, const char *inTarget,
                  const char *inSubstitute,
                  char *outFound ) {

    // repeatedly replace once until replacing fails
    
    char lastFound = true;
    char atLeastOneFound = false;
    char *returnString = stringDuplicate( inHaystack );

    while( lastFound ) {

        char *nextReturnString =
            replaceOnce( returnString, inTarget, inSubstitute, &lastFound );

        delete [] returnString;
        
        returnString = nextReturnString;

        if( lastFound ) {
            atLeastOneFound = true;
            }
        }

    *outFound = atLeastOneFound;
    
    return returnString;    
    }



char *replaceTargetListWithSubstituteList(
    const char *inHaystack,
    SimpleVector<char *> *inTargetVector,
    SimpleVector<char *> *inSubstituteVector ) {

    int numTargets = inTargetVector->size();

    char *newHaystack = stringDuplicate( inHaystack );

    char tagFound;
    
    for( int i=0; i<numTargets; i++ ) {
        char *newHaystackWithReplacements
            = replaceAll( newHaystack,
                          *( inTargetVector->getElement( i ) ),
                          *( inSubstituteVector->getElement( i ) ),
                          &tagFound );
        delete [] newHaystack;

        newHaystack = newHaystackWithReplacements;
        }

    return newHaystack;
    }



SimpleVector<char *> *tokenizeString( const char *inString ) {

    char *tempString = stringDuplicate( inString );

    char *restOfString = tempString;
    
    SimpleVector<char *> *foundTokens = new SimpleVector<char *>();

    SimpleVector<char> *currentToken = new SimpleVector<char>();


    while( restOfString[0] != '\0' ) {
        // characters remain

        // skip whitespace
        char nextChar = restOfString[0];
        while( nextChar == ' ' || nextChar == '\n' ||
               nextChar == '\r' || nextChar == '\t' ) {

            restOfString = &( restOfString[1] );
            nextChar = restOfString[0];
            }

        if( restOfString[0] != '\0' ) {

            // a token

            while( nextChar != ' ' && nextChar != '\n' &&
                   nextChar != '\r' && nextChar != '\t' &&
                   nextChar != '\0'  ) {

                // still not whitespace
                currentToken->push_back( nextChar );
                
                restOfString = &( restOfString[1] );
                nextChar = restOfString[0];
                }

            // reached end of token
            foundTokens->push_back( currentToken->getElementString() );
            currentToken->deleteAll();
            }        
        }

    delete [] tempString;

    delete currentToken;

    return foundTokens;
    }



char *autoSprintf( const char* inFormatString, ... ) {

    unsigned int bufferSize = 50;

    va_list argList;
    va_start( argList, inFormatString );

    char *buffer = new char[ bufferSize ];
    
    int stringLength =
        vsnprintf( buffer, bufferSize, inFormatString, argList );
    
    va_end( argList );


    if( stringLength != -1 ) {
        // follows C99 standard...
        // stringLength is the length of the string that would have been
        // written if the buffer was big enough

        //  not room for string and terminating \0 in bufferSize bytes
        if( (unsigned int)stringLength >= bufferSize ) {

            // need to reprint with a bigger buffer
            delete [] buffer;

            bufferSize = (unsigned int)( stringLength + 1 );

            va_list argList;
            va_start( argList, inFormatString );

            buffer = new char[ bufferSize ];

            // can simply use vsprintf now
            vsprintf( buffer, inFormatString, argList );
    
            va_end( argList );

            return buffer;
            }
        else {
            // buffer was big enough

            // trim the buffer to fit the string
            char *returnString = stringDuplicate( buffer );
            delete [] buffer;
            
            return returnString;
            }
        }
    else {
        // follows old ANSI standard
        // -1 means the buffer was too small

        // Note that some buggy non-C99 vsnprintf implementations
        // (notably MinGW)
        // do not return -1 if stringLength equals bufferSize (in other words,
        // if there is not enough room for the trailing \0).

        // Thus, we need to check for both
        //   (A)  stringLength == -1
        //   (B)  stringLength == bufferSize
        // below.
        
        // keep doubling buffer size until it's big enough
        while( stringLength == -1 || 
               (unsigned int)stringLength == bufferSize ) {

            delete [] buffer;

            if( (unsigned int)stringLength == bufferSize ) {
                // only occurs if vsnprintf implementation is buggy

                // might as well use the information, though
                // (instead of doubling the buffer size again)
                bufferSize = bufferSize + 1;
                }
            else {
                // double buffer size again
                bufferSize = 2 * bufferSize;
                }

            va_list argList;
            va_start( argList, inFormatString );

            buffer = new char[ bufferSize ];
    
            stringLength =
                vsnprintf( buffer, bufferSize, inFormatString, argList );
            
            va_end( argList );            
            }

        // trim the buffer to fit the string
        char *returnString = stringDuplicate( buffer );
        delete [] buffer;

        return returnString;
        }
    }