File: tjstring.cpp

package info (click to toggle)
odin 2.0.5-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,196 kB
  • sloc: cpp: 62,638; sh: 4,541; makefile: 779
file content (554 lines) | stat: -rw-r--r-- 14,718 bytes parent folder | download | duplicates (3)
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
#include "tjstring.h"
#include "tjarray.h"
#include "tjtools.h"
#include "tjlist.h"
#include "tjlog.h"
#include "tjcstd.h"
#include "tjtest.h"

#include "tjlog_code.h"

const char* StringComp::get_compName() {return "string";}
LOGGROUNDWORK(StringComp)


///////////////////////////////////////////////////////////////////////////////////////////////


STD_string replaceStr(const STD_string& s, const STD_string& searchstring,const STD_string& replacement,whichOccurences mode) {
  Log<StringComp> odinlog("","replaceStr");
  if(searchstring=="") return s;

  STD_string::size_type pos=0;
  int times=0;
  STD_string concat;
  STD_string result(s);

  ODINLOG(odinlog,normalDebug) << "trying to replace >" << searchstring << "< with >" << replacement <<  "< with mode " << mode << STD_endl;

  while( (pos=result.find(searchstring,pos)) != STD_string::npos) {

    concat = result.substr(0,pos);
    concat += replacement;
    unsigned int remainingstart=pos+searchstring.length();
    unsigned int length2end=result.length()-remainingstart;
    ODINLOG(odinlog,normalDebug) << "pos/remainingstart/length2end=" << pos << "/" << remainingstart << "/" << length2end << STD_endl;
    concat += result.substr(remainingstart,length2end);
    result=concat; // re-feed temporary result into this loop
    ODINLOG(odinlog,normalDebug) << "result(" << times << ")=" << result << STD_endl;
    pos+=replacement.length(); // Set to new position: Right after replacement
    times++;
    if(pos>=result.length()) break;
    if(mode==firstOccurence) break;
  }

  ODINLOG(odinlog,normalDebug) << "replacing " << times << " time(s) successful" << STD_endl;

  return result;
}

////////////////////////////////////////

STD_string extract(const STD_string& s, const STD_string& blockbegin,const STD_string& blockend,bool hierachical,int beginpos) {
  Log<StringComp> odinlog("","extract");
  int startpos,nextbegin,nextend,nocc,tmppos;
  STD_string tt;

  if(blockbegin=="") {
   startpos=beginpos;
   nextbegin=startpos+1;
  } else {
   STD_string::size_type startpos_st = s.find(blockbegin,beginpos);
   STD_string::size_type nextbegin_st= s.find(blockbegin,beginpos+1);

   if(startpos_st==STD_string::npos) startpos=-1;
   else startpos= startpos_st;

   if(nextbegin_st==STD_string::npos) nextbegin=-1;
   else nextbegin=nextbegin_st;
  }

  if(blockend=="") nextend=s.length();
  else {
    STD_string::size_type nextend_st=s.find(blockend,startpos+1);
    if(nextend_st==STD_string::npos) nextend=-1;
    else nextend=nextend_st;
  }

  ODINLOG(odinlog,normalDebug) << "startpos/nextbegin/nextend=" << startpos << "/" << nextbegin << "/" << nextend << STD_endl;

  if (hierachical) {
    unsigned int remainingstart=startpos+blockbegin.length();
    tt=s.substr(remainingstart,nextend-remainingstart);
    nocc=noccur(tt,blockbegin);
    while(nocc>0) {
      tmppos=nextend;
      for(int i=0;i<nocc;i++) {
        STD_string::size_type tmppos_st=s.find(blockend,tmppos+1);
        if(tmppos_st==STD_string::npos) tmppos=-1;
        else tmppos=tmppos_st;
      }
      if(tmppos <0 ) break;
      tt=s.substr(nextend,tmppos-nextend);
      nocc=noccur(tt,blockbegin);
      nextend=tmppos;
    }
  }

  if( (nextend < 0) || (startpos < 0) ) {
    return("");
  } else {
    unsigned int remainingstart=startpos+blockbegin.length();
    tt=s.substr(remainingstart,nextend-remainingstart);
  }
  return(tt);
}

////////////////////////////////////////

STD_string rmblock(const STD_string& s,const STD_string& blockbegin,const STD_string& blockend,bool rmbegin,bool rmend,bool rmall,bool hierachical) {
  STD_string::size_type beginpos=0;

  STD_string result(s);

  while( (beginpos=result.find(blockbegin,beginpos)) != STD_string::npos) {
    if(result.find(blockend,beginpos+blockbegin.length()) == STD_string::npos) break; // Check for matching blockend
    STD_string toberemoved;

    if(rmbegin) toberemoved+=blockbegin;
    else beginpos+=blockbegin.length();

    toberemoved+=extract(result,blockbegin,blockend,hierachical);

    if(rmend) toberemoved+=blockend;
    else beginpos+=blockend.length();

    result=replaceStr(result,toberemoved,"");

    if(!rmall) break;
  }

  return result;
}


////////////////////////////////////////


STD_string toupperstr (const STD_string& s) {
  STD_string t(s);
  unsigned int i;
  for(i=0;i<t.length();i++) t[i]=toupper(t[i]);
  return t;
}

////////////////////////////////////////

STD_string tolowerstr (const STD_string& s) {
  STD_string t(s);
  unsigned int i;
  for(i=0;i<t.length();i++) t[i]=tolower(t[i]);
  return t;
}

////////////////////////////////////////


STD_string ftos(double f, unsigned int digits, expFormat eformat) {
  STD_string result;
  const unsigned int buffsize=100;
  char buff[buffsize];

  STD_string format="%."+itos(digits);

  double absval=fabs(f);
  bool has_exp=true;
  if(eformat==neverExp) has_exp=false;
  if(eformat==autoExp) {
    double min=pow(10.0,-double(digits-2));
    double max=pow(10.0,+double(digits+1));
    if ( (absval>min && absval<max) || f==0.0) has_exp=false;
  }

  if(has_exp) format+="e";
  else        format+="f";

#ifdef HAVE_SNPRINTF
  snprintf(buff,buffsize,format.c_str(),f);
#else
  sprintf(buff,format.c_str(),f);
#endif

  if(eformat!=neverExp && atof(buff)==0.0 && f!=0.0) {
#ifdef HAVE_SNPRINTF
    snprintf(buff,buffsize,(" %."+itos(digits)+"e").c_str(),f); //consider very small values
#else
    sprintf(buff,(" %."+itos(digits)+"e").c_str(),f); //consider very small values
#endif
  }
  result=buff;

  // remove trailing zeroes
  if(!has_exp) {
    char *charptr=&buff[STD_string(buff).length()-1];
    while( *charptr == '0' && *(charptr-1) == '0' && charptr != &buff[1]) {
      *charptr='\0';
      charptr--;
    }
    result=buff;
  }
  return shrink(result);
}

////////////////////////////////////////

STD_string itos(int i, unsigned int maxabs) {
  const unsigned int buffsize=100;
  char buff[buffsize];
  if(maxabs) { // Costly log10 etc. only if necessary
    unsigned int mindigits=(unsigned int)log10(float(maxabs))+1;
#ifdef HAVE_SNPRINTF
    snprintf(buff,buffsize,"%0*i",mindigits,i);
#else
    sprintf(buff,"%0*i",mindigits,i);
#endif
  } else {  //fast version
#ifdef HAVE_SNPRINTF
    snprintf(buff,buffsize,"%i",i);
#else
    sprintf(buff,"%i",i);
#endif
  }
  return STD_string(buff);
}

STD_string ptos(const void* p) {
  const unsigned int buffsize=32;
  char buff[buffsize];
#ifdef HAVE_SNPRINTF
  snprintf(buff,buffsize,"%p",p);
#else
  sprintf(buff,"%p",p);
#endif
  return STD_string(buff);
}

////////////////////////////////////////

STD_string n_times(const STD_string& s,unsigned int n) {
 STD_string t;
 for(unsigned int i=0;i<n;i++) t+=s;
 return t;
}

////////////////////////////////////////

STD_string justificate(const STD_string& s, unsigned int indention,bool ignore_firstline, unsigned int linewidth) {
  Log<StringComp> odinlog("","justificate");
  STD_string result;
  if(indention>=linewidth) {
    ODINLOG(odinlog,errorLog) << "indention>=linewidth !" << STD_endl;
    return result;
  }

  STD_string blank(" ");

  svector tokenvector=tokens(s);
  STD_list<STD_string> linetokens;

  unsigned int linesize=0;

  unsigned int linewidthindent=linewidth-indention;

  bool firstline=true;

  for(unsigned int itoken=0; itoken<tokenvector.size(); itoken++) {
    unsigned int tokenlength=tokenvector[itoken].length();

    unsigned int ntokens=linetokens.size();

    if( (linesize+ntokens+tokenlength) > linewidthindent ) {
      int rest=linewidthindent-linesize;

      ivector blankvector;
      if(ntokens>1) {
        blankvector.resize(ntokens-1);
        while(rest>0) {
          for(unsigned int i=0; i<(ntokens-1); i++) {
            if(rest>0) blankvector[i]++;
            rest--;
          }
        }
      }

      if(firstline) {
         if(!ignore_firstline) result+=n_times(blank,indention);
         firstline=false;
      } else result+=n_times(blank,indention);

      unsigned int iblank=0;
      for(STD_list<STD_string>::iterator it=linetokens.begin(); it!=linetokens.end(); ++it) {
        result+=(*it);
        if(iblank<(ntokens-1)) result+=n_times(blank,blankvector[iblank]);
        iblank++;
      }
      result+="\n";

      linetokens.erase(linetokens.begin(),linetokens.end());
      linetokens.push_back(tokenvector[itoken]);
      linesize=tokenlength;
    } else {
      linetokens.push_back(tokenvector[itoken]);
      linesize+=tokenlength;
    }
  }

  if(linetokens.size()) {

    if(firstline) {
       if(!ignore_firstline) result+=n_times(blank,indention);
    } else result+=n_times(blank,indention);


    for(STD_list<STD_string>::iterator it=linetokens.begin(); it!=linetokens.end(); ++it) {
      result+=(*it);
      result+=blank;
    }
    result+="\n";
  }


  return result;
}


////////////////////////////////////////


int textbegin(const STD_string& s, int startpos, const char custom_separator) {
//  Log<StringComp> odinlog("","textbegin");
  int n=s.length();
  int pos=startpos;
  if( startpos<0 || startpos>=n) {
//    ODINLOG(odinlog,normalDebug) << "index(" << startpos << ") out of range(" << n << ")" << STD_endl;
    return -1;
  } else {
    if(custom_separator) {
      while(pos<n && custom_separator==s[pos]) pos++;
    } else {
      while(pos<n && isspace(s[pos])) pos++;
    }
  }
  return pos==n ? -1 : pos;
}

////////////////////////////////////////


int sepbegin(const STD_string& s, int startpos, const char custom_separator) {
//  Log<StringComp> odinlog("","sepbegin");
  int n=s.length();
  int pos=startpos;
  if( startpos<0 || startpos>=n) {
//    ODINLOG(odinlog,normalDebug) << "index(" << startpos << ") out of range(" << n << ")" << STD_endl;
    return -1;
  } else {
    if(custom_separator) {
      while(pos<n && custom_separator!=s[pos]) pos++;
    } else {
      while(pos<n && !isspace(s[pos])) pos++;
    }
  }
  return pos==n ? -1 : pos;
}


////////////////////////////////////////


STD_string shrink(const STD_string& s) {
  STD_string result(s);
  result=replaceStr(result," ","");
  result=replaceStr(result,"\n","");
  result=replaceStr(result,"\t","");
  result=replaceStr(result,"\r","");
  return result;
}

////////////////////////////////////////

int noccur(const STD_string& s, const STD_string& searchstring) {
  int noc=0;
  STD_string::size_type pos=0;
  while( (pos=s.find(searchstring,pos)) != STD_string::npos) {
    noc++;
    pos++;
  }
  return(noc);
}

////////////////////////////////////////


STD_string dos2unix(const STD_string& s) {
  unsigned int n=s.length();
  char* buff=new char[n+1];
  unsigned int ibuff=0;
  unsigned int istr=0;
  while(istr<n) {
    char currchar=s[istr];
    char nextchar=0;
    if(istr<(n-1)) nextchar=s[istr+1];
    if(currchar==char(0x0d) && nextchar==char(0x0a)) {
      buff[ibuff]=char(0x0a);
      istr++;
    } else buff[ibuff]=currchar;  
    istr++;
    ibuff++;
  }  
  buff[ibuff]='\0';

  STD_string result(buff);
  delete[] buff;
  
  return result;
}

///////////////////////////////////////////////////////////////////////////////////////////////

int load(STD_string& str, const STD_string& filename) {
  Log<StringComp> odinlog("","load");
#ifndef NO_FILEHANDLING

  LONGEST_INT file_size=filesize(filename.c_str());
  if(file_size<0) {
    ODINLOG(odinlog,warningLog) << "file >" << filename << "< not found" << STD_endl;
    return -1;
  }
  if(file_size==0) {
    str="";
    return 0;
  }
  FILE* file_ptr=ODIN_FOPEN(filename.c_str(),modestring(readMode));
  if(file_ptr==NULL) {
    ODINLOG(odinlog,errorLog) << "unable to open file >" << filename << "< - " << lasterr() << STD_endl;
    return -1;
  }

  char* s = new char [file_size+1];
  int i=fread(s,1,file_size,file_ptr);
  s[i]='\0';

  str=STD_string((const char*)s);

  if(file_ptr!=NULL) fclose(file_ptr);
  if(s) delete[] s;

#endif
  return 0;
}

////////////////////////////////////////

int write(const STD_string& str, const STD_string& filename, fopenMode mode) {
  Log<StringComp> odinlog("","write");
#ifndef NO_FILEHANDLING

  FILE* file_ptr=ODIN_FOPEN(filename.c_str(),modestring(mode));

  if(file_ptr==NULL) {
    ODINLOG(odinlog,errorLog) << "unable to create file:  >" << filename << "< - " << lasterr() << STD_endl;
    return -1;
  }

  fwrite(str.c_str(),sizeof(char),str.length(),file_ptr);
  if(file_ptr!=NULL) fclose(file_ptr);

#endif
  return 0;
}


/////////////////////////////////////////////////////////////////////////////////////////

#ifndef NO_UNIT_TEST


class StringTest : public UnitTest {

 public:
  StringTest() : UnitTest(StringComp::get_compName()) {}

 private:

  bool check() const {
    Log<UnitTest> odinlog(this,"check");

    STD_string printed, expected;


    expected="a";
    printed=replaceStr("abb","b","");
    if( expected!=printed ) {
      ODINLOG(odinlog,errorLog) << "replaceStr failed, got >" << printed << "< but expected >" << expected << "<" << STD_endl;
      return false;
    }


    expected="a";
    printed=shrink("\n\n \n\ta  ");
    if( expected!=printed ) {
      ODINLOG(odinlog,errorLog) << "shrink failed, got >" << printed << "< but expected >" << expected << "<" << STD_endl;
      return false;
    }


    expected="00123";
    printed=itos(123,10000);
    if( expected!=printed ) {
      ODINLOG(odinlog,errorLog) << "itos(1) failed, got >" << printed << "< but expected >" << expected << "<" << STD_endl;
      return false;
    }
    printed=itos(123,99999);
    if( expected!=printed ) {
      ODINLOG(odinlog,errorLog) << "itos(2) failed, got >" << printed << "< but expected >" << expected << "<" << STD_endl;
      return false;
    }


    expected="1234.5670";
    printed=ftos(1234.567);
    if( expected!=printed ) {
      ODINLOG(odinlog,errorLog) << "ftos(1) failed, got >" << printed << "< but expected >" << expected << "<" << STD_endl;
      return false;
    }
    expected="-1.00000e-03";
    printed=ftos(-0.001);
    if( expected!=printed ) {
      ODINLOG(odinlog,errorLog) << "ftos(2) failed, got >" << printed << "< but expected >" << expected << "<" << STD_endl;
      return false;
    }


    expected="bb";
    printed=extract("aaa[bb]cc", "[", "]");
    if( expected!=printed ) {
      ODINLOG(odinlog,errorLog) << "extract failed, got >" << printed << "< but expected >" << expected << "<" << STD_endl;
      return false;
    }

    expected="a(b)c";
    printed=extract("g(a(b)c)", "(", ")", true);
    if( expected!=printed ) {
      ODINLOG(odinlog,errorLog) << "extract(hierachical) failed, got >" << printed << "< but expected >" << expected << "<" << STD_endl;
      return false;
    }

    return true;
  }

};


void alloc_StringTest() {new StringTest();} // create test instance
#endif