root/trunk/StringFunctions.h

Revision 5, 16.5 kB (checked in by qbert, 6 years ago)

Initial ( and last :( ) commit

Line 
1 #ifndef STRINGFUNCTIONS_H
2 #define STRINGFUNCTIONS_H
3
4 #include "stdincludes.h"
5 #include "cs_filefunctions.h"
6 #include <cctype>
7 #include <algorithm>
8 #include <afxpriv.h>
9
10 class WhiteSpace
11 {
12 public:
13     static inline string ReplaceWhiteSpaceWithBlanks ( const string& str ) {
14
15         CString v(str.c_str() );
16
17         v.Replace("\r","");
18         v.Replace("\t","");
19         v.Replace("\n","");
20
21         return v.GetBuffer(0);
22
23     }
24    
25
26     static inline string ReplaceWithCodes ( const string& str ) {
27
28
29         CString v(str.c_str() );
30
31         v.Replace("\r","\\r");
32         v.Replace("\t","\\t");
33         v.Replace("\n","\\n");
34
35         return v.GetBuffer(0);
36
37     }
38
39     static inline string ReplaceCodesWithWhite(const string& str ) {
40
41         CString expands(str.c_str() );
42         expands.Replace("\\r","\r");
43         expands.Replace("\\t","\t");
44         expands.Replace("\\n","\n");
45
46         return expands.GetBuffer(0);
47     }
48    
49
50 };
51
52 inline bool FileIsReadOnly(const string& file )
53 {
54
55     DWORD code = GetFileAttributes(file.c_str() );
56
57     if ( code & FILE_ATTRIBUTE_READONLY ) return true;
58
59     return false;
60
61
62
63 }
64 inline bool isFullPath(const string& word )
65 {
66
67     if ( word.length() > 3 ) if ( word.substr(1,2) == ":\\" ) return true;
68     return false;
69
70 }
71 inline string ITOA(int x) {
72     char y[20];
73     sprintf(y,"%d",x);
74     return y;
75 }
76
77 inline string ReplaceCRandLF(string& buffer ) {
78     CString buf(buffer.c_str() );
79     buf.Replace("\r\n","REPLACE");
80     buf.Replace("\r","REPLACE");
81     buf.Replace("\n","REPLACE");
82     buf.Replace("REPLACE","\r\n");
83     return buf.GetBuffer(0);
84 }
85
86
87 inline void StripTrailingChars(string& str , char t ) {
88    
89
90     unsigned long pos = str.length() - 1;
91     if ( pos != string::npos ) {
92         while (pos > 0 && str[pos--] == t ) ; // find the last pos without 't'
93     }
94    
95     str = str.substr(0,pos+2);
96
97
98 }
99
100 inline string LowerCase(const string& u ) {
101     string ret = "";
102     for ( int i = 0;i < u.size();i++) { // dont lower the null zero , somehow that affect
103         ret += tolower(u[i] );
104     }
105
106     return ret;
107 }
108
109 inline char* getcwd()
110 {
111     char data[MAX_PATH+1];
112     GetCurrentDirectory(MAX_PATH,data );
113     return strdup(data);
114 }
115
116 string GetEmbeddedString(const string& marker, const string& buffer ) {
117         unsigned long pos = buffer.find_first_of(marker);
118         unsigned long pos2 = buffer.find_last_of(marker);
119         if ( pos != string::npos && pos2 != string::npos )
120                 return buffer.substr(pos+1,pos2);
121         return "";
122 }
123
124
125 inline int FindMatchingStrings(const string& str, const vector<string>& collection, int &startIndex ) {
126
127     int start = 0, count  = 0;
128     for ( int i = 0;i < collection.size();i++) {
129
130             if ( LowerCase(collection[i].substr(0,str.length() ) ) == LowerCase(str) ) {
131                 count++;
132                 if ( start == 0) start = i;
133             }
134
135     }
136
137     startIndex = start;
138     return count;
139
140
141 }
142
143
144 inline bool ParseFartLine(const string& buf, string& lineNumber, string& line ) {
145     unsigned long pos = 0 , pos1 = 0;
146
147     pos = buf.find("[");
148     pos1 = buf.find("]");
149
150     if ( pos == string::npos || pos1 == string::npos ) return false;
151
152     lineNumber = buf.substr(pos+1, pos1 - (pos + 1 ) );
153     line = buf.substr(pos1+1);
154
155     return true;
156
157 }
158
159 inline string StripFileName(const string& s) {
160     return s.substr(s.find_last_of("\\") + 1 );
161 }
162
163
164 inline string StripDirPath(const string& s) {
165     return s.substr(0,s.find_last_of("\\"));
166 }
167
168 inline string StripDirName(const string& s)
169 {  
170     return s.substr(s.find_last_of("\\") + 1);
171    
172 }
173
174 inline bool GetFileAndLineNumber(string& s,int& lineNumber, string& file ) {
175
176     unsigned long pos2, startPos = s.find_first_of(":") , pos = s.find_first_of("(");
177     if ( pos == string::npos || startPos == string::npos) return false;
178    
179    
180     file = s.substr(0,pos);
181     //AfxMessageBox(file.c_str());
182     pos2 = s.find_first_of(")");
183     lineNumber = atoi(s.substr(pos+1, pos2 - pos).c_str());
184     if ( lineNumber == 0 ) return false;
185     s = s.substr(startPos+1);
186
187
188     return true;
189    
190 }
191
192 inline void GetFontStyles(const string& s, int styles[3]) {
193
194     unsigned long pos = s.find_first_of("|");
195     styles[0] = atoi(s.substr(0,pos).c_str() );
196     unsigned long pos2 = s.find("|",pos+1);
197     styles[1] = atoi(s.substr(pos+1,pos2).c_str() );   
198     unsigned long pos3 = s.find("|",pos2+1);
199     styles[2] = atoi(s.substr(pos2+1,pos3).c_str() );   
200
201 }
202
203
204 inline void GetTabStyles(const string& s, int styles[2]) {
205
206     unsigned long pos = s.find_first_of("|");
207     styles[0] = atoi(s.substr(0,pos).c_str() );
208     unsigned long pos2 = s.find("|",pos+1);
209     styles[1] = atoi(s.substr(pos+1,pos2).c_str() );   
210 }
211
212 inline string ReadFile(const string& file) {   
213    
214     if (FileExists(file) )
215     {
216        
217         string buffer = "" , line = "";
218        
219         ifstream in(file.c_str() );
220         if ( in.good() ) {
221             while ( !in.eof () ) {
222                 std::getline(in,line);
223                 buffer += line + "\n";
224             }
225         }
226         in.close();
227        
228         return buffer;
229     }
230     else return "";
231     /*
232     
233       if ( FileExists(file_) ) {
234     
235     FILE* file = fopen(file_.c_str() ,"r");
236     fseek(file,0, SEEK_END);
237     int end = ftell(file) + 1;
238     char* data = new char[end];
239     fseek(file,0,SEEK_CUR);
240     fread((void*)data,1,end,file);
241     if ( data )
242     {
243         string ret(data);
244         fclose(file);
245         delete data;
246         return ret;
247     }
248     
249     fclose(file);
250     }
251     return "";
252     */
253 }
254
255 inline bool LastCharIsCurlyBrace(const string& buffer) {
256 //  char temp[10];
257     for (int i = buffer.size() - 1;i >= 0;i--) {
258         if (buffer[i] == '\t' || buffer[i] == ' ' || buffer[i] == '\n' || buffer[i] == '\r' || buffer[i] == 10 || buffer[i] == 13 ) continue;
259         else if (buffer[i] == '{') return true;
260         return false;
261     }
262     return false;
263 }
264    
265
266 inline string GetTabs(const string& buffer) {
267     string tabs = "";
268     for (int i = 0;i < buffer.size();i++) {
269         if (buffer[i] == '\t') tabs += "\t";
270         if (buffer[i] != '\t') return tabs; // use this so that only the first tabs are counted
271     }
272     return tabs;
273 }
274
275 inline bool ContainsWords(const string& word) {
276     for (int i = 0;i < word.size();i++) {
277         if (isalpha(word[i]) || isdigit(word[i])) return true;
278     }
279     return false;
280 }
281
282 inline bool IsAllWhiteSpace(const string& s) {
283
284     for ( int i = 0;i < s.length();i++) {
285         if (isspace(s[i] ) ) continue;
286         return false;
287     }
288     return true;
289
290 }
291
292 inline bool BeginsWithComment(const string& s) {
293     if (s.length() < 2) return false;
294     if (s[0] == '/' && s[1] == '/') return true;
295     if (s[0] == '/' && s[1] == '*') return true;
296     return false;
297
298 }
299    
300    
301 inline string GetDMDUnzipPath(const string& path ) {
302     unsigned int pos = path.find("dmd");
303     return path.substr(0,pos);
304 }
305
306
307 inline string GetDIGUnzipPath(const string& path ) {
308     unsigned int pos = path.find("dig");
309     return path.substr(0,pos);
310 }
311
312 inline bool ExistsIn(vector<string> & h , const string& n ) {
313     for ( int i = 0;i < h.size();i++) {
314         if ( h[i] == n ) return true;
315     }
316     return false;
317 }
318
319
320 template < class T >
321 inline  void RemoveDuplicates(vector<T>& output,vector<T>& uniques) {
322    
323     std::sort(output.begin(),output.end() );
324     std::unique_copy (output.begin(), output.end(),std::inserter(uniques, uniques.begin()));
325    
326 }
327
328 inline bool IsBrace(char ch) {
329     return ch == '[' || ch == ']' || ch == '(' || ch == ')' || ch == '{' || ch == '}';
330 }
331
332
333 inline string FileExtension(const string& s ) {
334     unsigned long pos = s.find_last_of(".");
335     return s.substr(pos+1);
336 }
337
338
339 inline void StripExtension(string& s ) {
340     unsigned long pos = s.find_last_of(".");
341     s = s.substr(0,pos);
342 }
343
344 inline string StripModifyStar(CString title)
345 {
346     title.Replace("*","");
347     return title.GetBuffer(0);
348    
349 }
350 inline string stripl(const string&  s)
351 {
352     int i;
353
354     for (i = 0; i < s.length(); i++)
355     {
356     if (!isspace(s[i]))
357         break;
358     }
359     return s.substr(i,s.length() ) ;
360 }
361
362 inline string stripr(const string& s)
363 {
364     int i;
365
366     for (i = s.length(); i > 0; i--)
367     {
368     if (!isspace(s[i - 1]))
369         break;
370     }
371     return s.substr(0,i);
372 }
373
374 inline string strip(const string& s)
375 {
376     return stripr(stripl(s));
377 }
378
379
380 inline string ReplaceConstants(string& s, const string& name, const string& pname) {
381
382     unsigned long pos = 0 , inc = 0;
383
384     CTime _t = CTime::GetCurrentTime();
385     CString t;
386     t.Format("%d / %d / %d",_t.GetMonth(),_t.GetDay(), _t.GetYear());
387
388     CString time;
389     time.Format("%d:%d:%d",_t.GetHour(), _t.GetMinute(),_t.GetSecond());
390
391    
392     pos = 0;
393     inc = 0;
394    
395     while ( (pos = s.find("PROJECTNAME",inc) ) != string::npos  ) {
396         s.replace(pos,11,pname.c_str() );
397     }
398
399     pos = 0;
400     inc = 0;
401
402     while ( (pos = s.find("DATE",inc) ) != string::npos  ) {
403         s.replace(pos,4,(LPCSTR)t);
404     }
405
406     pos = 0;
407     inc = 0;
408
409     while ( (pos = s.find("TIME",inc) ) != string::npos  ) {
410         s.replace(pos,4,(LPCSTR)time);
411     }
412
413
414     pos = 0;
415     inc = 0;
416
417     while ( (pos = s.find("NAME",inc) ) != string::npos  ) {
418         s.replace(pos,4,name.c_str() );
419     }
420
421
422
423     return s;
424 }      
425
426 inline string ReplaceAll(const string& _line , const string& findString, const string& replaceString, bool ignoreCase = false )
427 {
428
429     CString line(_line.c_str() );
430     int pos = 0;
431
432     if ( ignoreCase ) {
433         CString lower = line;
434         CString fs(findString.c_str() );
435         fs.MakeLower();
436         lower.MakeLower();
437
438 //      ElephantMessageBox(lower );
439 //      ElephantMessageBox(fs );
440        
441         while ( (pos = lower.Find(fs) )  != -1 ) {
442            
443             line.Delete(pos , findString.length());
444             line.Insert(pos,replaceString.c_str() );
445
446             // replace for lower also so it will just traverse the string
447             lower.Delete(pos , findString.length());
448             lower.Insert(pos,replaceString.c_str() );
449            
450         }
451
452     }
453     else {
454        
455         line.Replace(findString.c_str() , replaceString.c_str() );
456     }
457
458     return line.GetBuffer(0);
459    
460 }
461
462 string shortPathName(const string& path );
463
464 inline string TranslateToolsMenuConstants(const string& str, const string& currentFile,const string& projectExe,
465                       const string& projectDir,const vector<string>& pfiles ) {
466     string projectFiles = "";
467     for ( int i = 0;i < pfiles.size();i++) {       
468         i + 1 == pfiles.size () ?
469             projectFiles += "\"" + pfiles[i] + "\""
470             :
471             projectFiles += "\"" + pfiles[i] + "\" ";
472
473     }
474
475     CString buf(str.c_str() );
476     buf.Replace("CURRENTFILE",string("\"" + currentFile + "\"" ).c_str() );
477     buf.Replace("PROJECTEXE",string("\"" + projectExe + "\"" ).c_str() );
478     buf.Replace("PROJECTDIR",string("\"" + projectDir + "\"").c_str() );
479     buf.Replace("PROJECTFILES",projectFiles.c_str() );
480
481     return buf.GetBuffer(0);
482 }
483
484 inline BOOL  getLongPathName(const string & cs, CString &sLongPath)
485 {
486         CString sShortPath(cs.c_str() );
487         USES_CONVERSION;
488
489         LPSHELLFOLDER   psfDesktop = NULL;
490         ULONG                   chEaten = 0;
491         LPITEMIDLIST    pidlShellItem = NULL;
492         WCHAR                   szLongPath[_MAX_PATH] = { 0 };
493         BOOL                    bResult = TRUE;
494
495         // Get the Desktop's shell folder interface
496         HRESULT hr = SHGetDesktopFolder(&psfDesktop);
497
498         LPCTSTR lpsz = (LPCTSTR)sShortPath;
499         LPWSTR  lpwShortPath = A2W(lpsz);
500
501         // Request an ID list (relative to the desktop) for the short pathname
502         hr = psfDesktop->ParseDisplayName(NULL, NULL, lpwShortPath, &chEaten, &pidlShellItem, NULL);
503         psfDesktop->Release(); // Release the desktop's IShellFolder
504
505         if(FAILED(hr))
506         {
507                 // If we couldn't get an ID list for short pathname, it must not exist.
508                 sLongPath.Empty();
509                 bResult = FALSE;
510         }
511         else
512         {
513                 // We did get an ID list, convert it to a long pathname
514                 SHGetPathFromIDListW(pidlShellItem, szLongPath);
515  
516                 // Free the ID list allocated by ParseDisplayName
517                 LPMALLOC pMalloc = NULL;
518                 SHGetMalloc(&pMalloc);
519                 pMalloc->Free(pidlShellItem);
520                 pMalloc->Release();
521                 sLongPath = W2A(szLongPath);
522         }
523
524         return bResult;
525
526 } 
527
528
529
530
531 inline bool IsIn(const string& t, const vector<string>& v ) {
532     for ( int i = 0;i < v.size();i++) {
533         if ( v[i] == t ) return true;
534     }
535     return false;
536 }
537
538 inline void AdvanceWhiteSpaceOrComment(const string& line, int& pos ) {
539
540     bool isInLineComment = false, isInFullComment = false;
541
542     for ( int i = 0;i < line.size();i ++ ) {
543
544         if ( isspace(line[i] ) ) {
545             continue;
546         }   
547         else {
548            
549             if ( line[i] == '/' ) { // check to see if start of comment
550
551                 if ( line.length() > i + 1 ) {
552                     if ( line[i + 1] == '*') {
553                         i++;
554                         isInFullComment = true;
555                         continue;
556                     }
557                     else if ( line[i + 1] == '/' ) {
558                         i++;
559                         isInLineComment = true;
560                         /* */                       continue;
561                     }
562                 }
563
564                 if ( line.length() > i - 1 ) {
565                     if ( line[i - 1 ] == '*' ) {
566                         isInFullComment = false;
567                         isInLineComment = false;
568                     }
569                 }
570             }
571             else if  ( line[i] == '\n' ) {
572                 isInLineComment = false;
573                 continue;
574             }
575             else if ( isInLineComment || isInFullComment ) {
576                 continue;
577             }
578             else {
579                 pos = i;
580                 return;
581             }
582         }
583
584     }
585
586 }  
587
588 bool NextCharIsBackward(char ch , const string& backwardText, int skipNo );
589 bool NextCharIs(char ch , const string& backwardText , int skipNo);
590
591 inline bool CheckForCombo(const string& start, char end, const string& line ) {
592
593     // check that the first part matches
594     if ( line.length() > start.length () ) {
595         if ( line.substr(0,start.length () ) != start ) {
596             return false;
597         }
598     }
599     else return false;
600
601     int i = start.length();
602     int pos = 0;
603
604     if ( i < line.length() ) {
605
606         AdvanceWhiteSpaceOrComment(line.substr(i) , pos );
607         CString buf(line[pos + i] );
608         if ( pos + i  <= line.length () ) {
609             if ( line[pos + i] == end ) return true;
610             else {
611                 return false;
612             }
613         }
614     }
615    
616     return false;
617        
618 }
619
620 inline bool StartsWith( const string& match, const string& text ) {
621
622     if ( text.length() > match.length () )
623         if ( text.substr(0,match.length()) == match )
624             return true;
625    
626     return false;
627 }
628 inline void Reverse(string& line )
629 {
630
631   std::reverse(line.begin(),line.end() );
632
633 }
634
635 bool StartsWithBackward(const string& match, const string& backwardText );
636 void AdvanceToWhiteSpaceOrChar(const string& text, int & pos, char c );
637 void AdvanceToWhiteSpace(const string& text, int & pos ) ;
638
639 void AdvanceToWhiteSpaceOrCharBackward(const string& text, int & pos, char c );
640 void AdvanceToWhiteSpaceBackward(const string& text, int & pos ) ;
641
642 inline bool IsWord( const string& text ) {
643     if ( !text.size() ) return false;
644     for ( int i = 0 ;i < text.size();i++) {
645         if ( isalpha(text[i]) || isdigit(text[i]) || text[i] == '_' || text[i] == '-' ) continue;
646         else return false;
647
648     }
649     return true;
650 }
651
652 inline bool IsType( const string& text ) {
653     if ( !text.size() ) return false;
654     for ( int i = 0 ;i < text.size();i++) {
655         if ( isalpha(text[i]) || isdigit(text[i]) || text[i] == '_' || text[i] == '-'
656              || text[i] == '['
657              || text[i] == ']'
658              || text[i] == '*'
659              || text[i] == '.'
660             ) continue;
661         else return false;
662
663     }
664     return true;
665 }
666
667
668
669 bool MatchesFunctionDefinition (const string& text) ;
670
671
672 void Split(const string& str, const string& delim, vector<string>& items );
673 void Split(const string& buffer, string& result1, string& result2 );
674 string Join(const vector<string>& items, const string & delim);
675 void GetKeysForMap(map<string,vector<string> > & , vector<string>  &);
676 void GetKeysForMap(map<string,string> & , vector<string>  &);
677 void RemoveFileFromMap(map<string,vector<string> > & myMap,const string& mySet, const string& myFile ) ;
678
679 template<typename T> void RemoveFromVector(vector<T>& words, const vector<T>& word )
680 {
681
682     for ( int i = 0 ;i < word.size();i++)
683     {
684
685         for ( int j = 0;j < words.size();j++) {
686             if ( words[j] == word[i] ) {
687                 words.erase(j + words.begin());
688                 break;
689             }
690         }
691
692     }
693 }
694 template<typename T> void RemoveFromVector(vector<T>& words, const T& word )
695 {
696     for ( int i = 0;i < words.size();i++)
697     {
698         if ( words[i] == word ) {
699             words.erase(i + words.begin () );
700             break;
701         }
702
703     }
704
705 }
706 void GetAbbExpansion(const string& exp, string& expands, int & cursor, bool& tabs );
707 string SetAbbExpansion(CString& exp,CString & cursor, CString& tabs );
708
709
710
711 class Strtok {
712
713  public:
714     Strtok (string *_str, string delim,
715             bool returnTokens);
716     Strtok (string *_str, string delim);
717     Strtok (string *_str);
718     Strtok ();
719     ~Strtok ();
720
721     void SkipDelimiters ();
722     bool HasMoreTokens ();
723     string NextToken(void);
724     bool NextToken(string &_str);
725     int GetStart (void);
726     int CountTokens();
727     void Reset (string *_str);
728     void Reset (string *_str, bool returnTokens);
729     void Reset (string *_str, string delim, bool returnTokens = false);
730  
731  private:
732     int currentPosition;
733     int maxPosition;
734     string* str;
735     string delimiters;
736     bool retTokens;
737 };
738
739 #endif
Note: See TracBrowser for help on using the browser.