2 * Copyright (C) 2005-2013 Team XBMC
5 * This Program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2, or (at your option)
10 * This Program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with XBMC; see the file COPYING. If not, see
17 * <http://www.gnu.org/licenses/>.
20 //-----------------------------------------------------------------------
22 // File: StringUtils.cpp
24 // Purpose: ATL split string utility
25 // Author: Paul J. Weiss
27 // Modified to use J O'Leary's CStdString class by kraqh3d
29 //------------------------------------------------------------------------
32 #include "StringUtils.h"
33 #include "utils/RegExp.h"
34 #include "utils/fstrcmp.h"
41 #define FORMAT_BLOCK_SIZE 2048 // # of bytes to increment per try
45 const char* ADDON_GUID_RE = "^(\\{){0,1}[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}(\\}){0,1}$";
47 /* empty string for use in returns by ref */
48 const CStdString StringUtils::EmptyString = "";
49 const std::string StringUtils::Empty = "";
50 CStdString StringUtils::m_lastUUID = "";
52 string StringUtils::Format(const char *fmt, ...)
56 string str = FormatV(fmt, args);
62 string StringUtils::FormatV(const char *fmt, va_list args)
67 int size = FORMAT_BLOCK_SIZE;
70 char *cstr = reinterpret_cast<char*>(malloc(sizeof(char) * size));
76 va_copy(argCopy, args);
78 int nActual = vsnprintf(cstr, size, fmt, argCopy);
81 if (nActual > -1 && nActual < size) // We got a valid result
83 string str(cstr, nActual);
87 if (nActual > -1) // Exactly what we will need (glibc 2.1)
89 else // Let's try to double the size (glibc 2.0)
92 char *new_cstr = reinterpret_cast<char*>(realloc(cstr, sizeof(char) * size));
106 void StringUtils::ToUpper(string &str)
108 transform(str.begin(), str.end(), str.begin(), ::toupper);
111 void StringUtils::ToLower(string &str)
113 transform(str.begin(), str.end(), str.begin(), ::tolower);
116 bool StringUtils::EqualsNoCase(const std::string &str1, const std::string &str2)
118 return EqualsNoCase(str1.c_str(), str2.c_str());
121 bool StringUtils::EqualsNoCase(const std::string &str1, const char *s2)
123 return EqualsNoCase(str1.c_str(), s2);
126 bool StringUtils::EqualsNoCase(const char *s1, const char *s2)
128 int c1, c2; // Yes, because the return type of tolower() is int.
129 // To make these chars would be to introduce an unnecesary extra bitmask/zero-extend (effectively caller-narowing) into the binary.
132 c1 = ::tolower(*s1++);
133 c2 = ::tolower(*s2++);
134 if (c1 != c2) // This includes the possibility that one of the characters is the null-terminator, which implies a string mismatch.
136 } while (c2 != '\0'); // At this point, we know c1 == c2, so there's no need to test them both.
140 string StringUtils::Left(const string &str, size_t count)
142 count = max((size_t)0, min(count, str.size()));
143 return str.substr(0, count);
146 string StringUtils::Mid(const string &str, size_t first, size_t count /* = string::npos */)
148 if (first + count > str.size())
149 count = str.size() - first;
151 if (first > str.size())
154 ASSERT(first + count <= str.size());
156 return str.substr(first, count);
159 string StringUtils::Right(const string &str, size_t count)
161 count = max((size_t)0, min(count, str.size()));
162 return str.substr(str.size() - count);
165 std::string& StringUtils::Trim(std::string &str)
168 return TrimRight(str);
171 // hack to ensure that std::string::iterator will be dereferenced as _unsigned_ char
172 // without this hack "TrimX" functions failed on Win32 with UTF-8 strings
173 static int isspace_c(char c)
175 return ::isspace((unsigned char)c);
178 std::string& StringUtils::TrimLeft(std::string &str)
180 str.erase(str.begin(), ::find_if(str.begin(), str.end(), ::not1(::ptr_fun(isspace_c))));
184 std::string& StringUtils::TrimRight(std::string &str)
186 str.erase(::find_if(str.rbegin(), str.rend(), ::not1(::ptr_fun(isspace_c))).base(), str.end());
190 std::string& StringUtils::RemoveDuplicatedSpacesAndTabs(std::string& str)
192 std::string::iterator it = str.begin();
193 bool onSpace = false;
194 while(it != str.end())
217 int StringUtils::Replace(string &str, char oldChar, char newChar)
219 int replacedChars = 0;
220 for (string::iterator it = str.begin(); it != str.end(); it++)
229 return replacedChars;
232 int StringUtils::Replace(std::string &str, const std::string &oldStr, const std::string &newStr)
237 int replacedChars = 0;
240 while (index < str.size() && (index = str.find(oldStr, index)) != string::npos)
242 str.replace(index, oldStr.size(), newStr);
243 index += newStr.size();
247 return replacedChars;
250 bool StringUtils::StartsWith(const std::string &str1, const std::string &str2)
252 return str1.compare(0, str2.size(), str2) == 0;
255 bool StringUtils::StartsWith(const std::string &str1, const char *s2)
257 return StartsWith(str1.c_str(), s2);
260 bool StringUtils::StartsWith(const char *s1, const char *s2)
272 bool StringUtils::StartsWithNoCase(const std::string &str1, const std::string &str2)
274 return StartsWithNoCase(str1.c_str(), str2.c_str());
277 bool StringUtils::StartsWithNoCase(const std::string &str1, const char *s2)
279 return StartsWithNoCase(str1.c_str(), s2);
282 bool StringUtils::StartsWithNoCase(const char *s1, const char *s2)
286 if (::tolower(*s1) != ::tolower(*s2))
294 bool StringUtils::EndsWith(const std::string &str1, const std::string &str2)
296 if (str1.size() < str2.size())
298 return str1.compare(str1.size() - str2.size(), str2.size(), str2) == 0;
301 bool StringUtils::EndsWith(const std::string &str1, const char *s2)
303 size_t len2 = strlen(s2);
304 if (str1.size() < len2)
306 return str1.compare(str1.size() - len2, len2, s2) == 0;
309 bool StringUtils::EndsWithNoCase(const std::string &str1, const std::string &str2)
311 if (str1.size() < str2.size())
313 const char *s1 = str1.c_str() + str1.size() - str2.size();
314 const char *s2 = str2.c_str();
317 if (::tolower(*s1) != ::tolower(*s2))
325 bool StringUtils::EndsWithNoCase(const std::string &str1, const char *s2)
327 size_t len2 = strlen(s2);
328 if (str1.size() < len2)
330 const char *s1 = str1.c_str() + str1.size() - len2;
333 if (::tolower(*s1) != ::tolower(*s2))
341 void StringUtils::JoinString(const CStdStringArray &strings, const CStdString& delimiter, CStdString& result)
344 for(CStdStringArray::const_iterator it = strings.begin(); it != strings.end(); it++ )
345 result += (*it) + delimiter;
348 result.Delete(result.size()-delimiter.size(), delimiter.size());
351 CStdString StringUtils::JoinString(const CStdStringArray &strings, const CStdString& delimiter)
354 JoinString(strings, delimiter, result);
358 CStdString StringUtils::Join(const vector<string> &strings, const CStdString& delimiter)
360 CStdStringArray strArray;
361 for (unsigned int index = 0; index < strings.size(); index++)
362 strArray.push_back(strings.at(index));
364 return JoinString(strArray, delimiter);
367 // Splits the string input into pieces delimited by delimiter.
368 // if 2 delimiters are in a row, it will include the empty string between them.
369 // added MaxStrings parameter to restrict the number of returned substrings (like perl and python)
370 int StringUtils::SplitString(const CStdString& input, const CStdString& delimiter, CStdStringArray &results, unsigned int iMaxStrings /* = 0 */)
374 int sizeS2 = delimiter.GetLength();
375 int isize = input.GetLength();
379 vector<unsigned int> positions;
381 newPos = input.Find (delimiter, 0);
385 results.push_back(input);
389 while ( newPos > iPos )
391 positions.push_back(newPos);
393 newPos = input.Find (delimiter, iPos + sizeS2);
396 // numFound is the number of delimiters which is one less
397 // than the number of substrings
398 unsigned int numFound = positions.size();
399 if (iMaxStrings > 0 && numFound >= iMaxStrings)
400 numFound = iMaxStrings - 1;
402 for ( unsigned int i = 0; i <= numFound; i++ )
410 s = input.Mid( i, positions[i] );
414 int offset = positions[i - 1] + sizeS2;
415 if ( offset < isize )
418 s = input.Mid(offset);
420 s = input.Mid( positions[i - 1] + sizeS2,
421 positions[i] - positions[i - 1] - sizeS2 );
424 results.push_back(s);
426 // return the number of substrings
427 return results.size();
430 CStdStringArray StringUtils::SplitString(const CStdString& input, const CStdString& delimiter, unsigned int iMaxStrings /* = 0 */)
432 CStdStringArray result;
433 SplitString(input, delimiter, result, iMaxStrings);
437 vector<string> StringUtils::Split(const std::string& input, const std::string& delimiter, unsigned int iMaxStrings /* = 0 */)
439 CStdStringArray result;
440 SplitString(input, delimiter, result, iMaxStrings);
442 vector<string> strArray;
443 for (unsigned int index = 0; index < result.size(); index++)
444 strArray.push_back(result.at(index));
449 // returns the number of occurrences of strFind in strInput.
450 int StringUtils::FindNumber(const CStdString& strInput, const CStdString &strFind)
452 int pos = strInput.Find(strFind, 0);
457 pos = strInput.Find(strFind, pos + 1);
462 // Compares separately the numeric and alphabetic parts of a string.
463 // returns negative if left < right, positive if left > right
464 // and 0 if they are identical (essentially calculates left - right)
465 int64_t StringUtils::AlphaNumericCompare(const wchar_t *left, const wchar_t *right)
467 wchar_t *l = (wchar_t *)left;
468 wchar_t *r = (wchar_t *)right;
472 const collate<wchar_t>& coll = use_facet< collate<wchar_t> >( locale() );
474 while (*l != 0 && *r != 0)
476 // check if we have a numerical value
477 if (*l >= L'0' && *l <= L'9' && *r >= L'0' && *r <= L'9')
481 while (*ld >= L'0' && *ld <= L'9' && ld < l + 15)
482 { // compare only up to 15 digits
488 while (*rd >= L'0' && *rd <= L'9' && rd < r + 15)
489 { // compare only up to 15 digits
491 rnum += *rd++ - L'0';
493 // do we have numbers?
495 { // yes - and they're different!
502 // do case less comparison
504 if (lc >= L'A' && lc <= L'Z')
507 if (rc >= L'A' && rc <= L'Z')
510 // ok, do a normal comparison, taking current locale into account. Add special case stuff (eg '(' characters)) in here later
511 if ((cmp_res = coll.compare(&lc, &lc + 1, &rc, &rc + 1)) != 0)
525 return 0; // files are the same
528 int StringUtils::DateStringToYYYYMMDD(const CStdString &dateString)
530 CStdStringArray days;
531 int splitCount = StringUtils::SplitString(dateString, "-", days);
533 return atoi(days[0].c_str());
534 else if (splitCount == 2)
535 return atoi(days[0].c_str())*100+atoi(days[1].c_str());
536 else if (splitCount == 3)
537 return atoi(days[0].c_str())*10000+atoi(days[1].c_str())*100+atoi(days[2].c_str());
542 long StringUtils::TimeStringToSeconds(const CStdString &timeString)
544 CStdString strCopy(timeString);
545 strCopy.TrimLeft(" \n\r\t");
546 strCopy.TrimRight(" \n\r\t");
547 if(StringUtils::EndsWithNoCase(strCopy, " min"))
549 // this is imdb format of "XXX min"
550 return 60 * atoi(strCopy.c_str());
554 CStdStringArray secs;
555 StringUtils::SplitString(strCopy, ":", secs);
557 for (unsigned int i = 0; i < 3 && i < secs.size(); i++)
560 timeInSecs += atoi(secs[i]);
566 CStdString StringUtils::SecondsToTimeString(long lSeconds, TIME_FORMAT format)
568 int hh = lSeconds / 3600;
569 lSeconds = lSeconds % 3600;
570 int mm = lSeconds / 60;
571 int ss = lSeconds % 60;
573 if (format == TIME_FORMAT_GUESS)
574 format = (hh >= 1) ? TIME_FORMAT_HH_MM_SS : TIME_FORMAT_MM_SS;
576 if (format & TIME_FORMAT_HH)
577 strHMS.AppendFormat("%02.2i", hh);
578 else if (format & TIME_FORMAT_H)
579 strHMS.AppendFormat("%i", hh);
580 if (format & TIME_FORMAT_MM)
581 strHMS.AppendFormat(strHMS.IsEmpty() ? "%02.2i" : ":%02.2i", mm);
582 if (format & TIME_FORMAT_SS)
583 strHMS.AppendFormat(strHMS.IsEmpty() ? "%02.2i" : ":%02.2i", ss);
587 bool StringUtils::IsNaturalNumber(const CStdString& str)
590 // allow whitespace,digits,whitespace
591 while (i < str.size() && isspace((unsigned char) str[i]))
593 while (i < str.size() && isdigit((unsigned char) str[i]))
597 while (i < str.size() && isspace((unsigned char) str[i]))
599 return i == str.size() && n > 0;
602 bool StringUtils::IsInteger(const CStdString& str)
605 // allow whitespace,-,digits,whitespace
606 while (i < str.size() && isspace((unsigned char) str[i]))
608 if (i < str.size() && str[i] == '-')
610 while (i < str.size() && isdigit((unsigned char) str[i]))
614 while (i < str.size() && isspace((unsigned char) str[i]))
616 return i == str.size() && n > 0;
619 void StringUtils::RemoveCRLF(CStdString& strLine)
621 while ( strLine.size() && (strLine.Right(1) == "\n" || strLine.Right(1) == "\r") )
623 strLine = strLine.Left(std::max(0, (int)strLine.size() - 1));
627 CStdString StringUtils::SizeToString(int64_t size)
630 const char prefixes[] = {' ','k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'};
632 double s = (double)size;
633 while (i < sizeof(prefixes)/sizeof(prefixes[0]) && s >= 1000.0)
640 strLabel.Format("%.0lf %cB ", s, prefixes[i]);
642 strLabel.Format("%.1lf %cB", s, prefixes[i]);
644 strLabel.Format("%.2lf %cB", s, prefixes[i]);
649 // return -1 if not, else return the utf8 char length.
650 int IsUTF8Letter(const unsigned char *str)
653 // unicode -> utf8 table: http://www.utf8-chartable.de/
654 // latin characters in unicode: http://en.wikipedia.org/wiki/Latin_characters_in_Unicode
655 unsigned char ch = str[0];
658 if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
662 unsigned char ch2 = str[1];
665 // check latin 1 letter table: http://en.wikipedia.org/wiki/C1_Controls_and_Latin-1_Supplement
666 if (ch == 0xC3 && ch2 >= 0x80 && ch2 <= 0xBF && ch2 != 0x97 && ch2 != 0xB7)
668 // check latin extended A table: http://en.wikipedia.org/wiki/Latin_Extended-A
669 if (ch >= 0xC4 && ch <= 0xC7 && ch2 >= 0x80 && ch2 <= 0xBF)
671 // check latin extended B table: http://en.wikipedia.org/wiki/Latin_Extended-B
672 // and International Phonetic Alphabet: http://en.wikipedia.org/wiki/IPA_Extensions_(Unicode_block)
673 if (((ch == 0xC8 || ch == 0xC9) && ch2 >= 0x80 && ch2 <= 0xBF)
674 || (ch == 0xCA && ch2 >= 0x80 && ch2 <= 0xAF))
679 size_t StringUtils::FindWords(const char *str, const char *wordLowerCase)
681 // NOTE: This assumes word is lowercase!
682 unsigned char *s = (unsigned char *)str;
685 // start with a compare
686 unsigned char *c = s;
687 unsigned char *w = (unsigned char *)wordLowerCase;
689 while (same && *c && *w)
691 unsigned char lc = *c++;
692 if (lc >= 'A' && lc <= 'Z')
695 if (lc != *w++) // different
698 if (same && *w == 0) // only the same if word has been exhausted
699 return (const char *)s - str;
701 // otherwise, skip current word (composed by latin letters) or number
703 if (*s >= '0' && *s <= '9')
706 while (*s >= '0' && *s <= '9') ++s;
708 else if ((l = IsUTF8Letter(s)) > 0)
711 while ((l = IsUTF8Letter(s)) > 0) s += l;
715 while (*s && *s == ' ') s++;
717 // and repeat until we're done
720 return CStdString::npos;
723 // assumes it is called from after the first open bracket is found
724 int StringUtils::FindEndBracket(const CStdString &str, char opener, char closer, int startPos)
727 for (unsigned int i = startPos; i < str.size(); i++)
729 if (str[i] == opener)
731 else if (str[i] == closer)
739 return (int)CStdString::npos;
742 void StringUtils::WordToDigits(CStdString &word)
744 static const char word_to_letter[] = "22233344455566677778889999";
746 for (unsigned int i = 0; i < word.size(); ++i)
747 { // NB: This assumes ascii, which probably needs extending at some point.
748 char letter = word[i];
749 if ((letter >= 'a' && letter <= 'z')) // assume contiguous letter range
751 word[i] = word_to_letter[letter-'a'];
753 else if (letter < '0' || letter > '9') // We want to keep 0-9!
755 word[i] = ' '; // replace everything else with a space
760 CStdString StringUtils::CreateUUID()
762 /* This function generate a DCE 1.1, ISO/IEC 11578:1996 and IETF RFC-4122
763 * Version 4 conform local unique UUID based upon random number generation.
766 char *pUuidStr = UuidStrTmp;
769 static bool m_uuidInitialized = false;
770 if (!m_uuidInitialized)
772 /* use current time as the seed for rand()*/
774 m_uuidInitialized = true;
777 /*Data1 - 8 characters.*/
778 for(i = 0; i < 8; i++, pUuidStr++)
779 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
781 /*Data2 - 4 characters.*/
783 for(i = 0; i < 4; i++, pUuidStr++)
784 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
786 /*Data3 - 4 characters.*/
788 for(i = 0; i < 4; i++, pUuidStr++)
789 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
791 /*Data4 - 4 characters.*/
793 for(i = 0; i < 4; i++, pUuidStr++)
794 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
796 /*Data5 - 12 characters.*/
798 for(i = 0; i < 12; i++, pUuidStr++)
799 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
803 m_lastUUID = UuidStrTmp;
807 bool StringUtils::ValidateUUID(const CStdString &uuid)
810 guidRE.RegComp(ADDON_GUID_RE);
811 return (guidRE.RegFind(uuid.c_str()) == 0);
814 double StringUtils::CompareFuzzy(const CStdString &left, const CStdString &right)
816 return (0.5 + fstrcmp(left.c_str(), right.c_str(), 0.0) * (left.length() + right.length())) / 2.0;
819 int StringUtils::FindBestMatch(const CStdString &str, const CStdStringArray &strings, double &matchscore)
825 for (CStdStringArray::const_iterator it = strings.begin(); it != strings.end(); it++, i++)
827 int maxlength = max(str.length(), it->length());
828 double score = StringUtils::CompareFuzzy(str, *it) / maxlength;
829 if (score > matchscore)
838 bool StringUtils::ContainsKeyword(const CStdString &str, const CStdStringArray &keywords)
840 for (CStdStringArray::const_iterator it = keywords.begin(); it != keywords.end(); it++)
842 if (str.find(*it) != str.npos)
848 size_t StringUtils::utf8_strlen(const char *s)
853 if ((*s++ & 0xC0) != 0x80)
859 std::string StringUtils::Paramify(const std::string ¶m)
861 std::string result = param;
863 StringUtils::Replace(result, "\\", "\\\\");
864 // escape double quotes
865 StringUtils::Replace(result, "\"", "\\\"");
867 // add double quotes around the whole string
868 return "\"" + result + "\"";
871 void StringUtils::Tokenize(const std::string& input, std::vector<std::string>& tokens, const std::string& delimiters)
873 // Tokenize ripped from http://www.linuxselfhelp.com/HOWTO/C++Programming-HOWTO-7.html
874 // Skip delimiters at beginning.
875 string::size_type lastPos = input.find_first_not_of(delimiters, 0);
876 // Find first "non-delimiter".
877 string::size_type pos = input.find_first_of(delimiters, lastPos);
879 while (string::npos != pos || string::npos != lastPos)
881 // Found a token, add it to the vector.
882 tokens.push_back(input.substr(lastPos, pos - lastPos));
883 // Skip delimiters. Note the "not_of"
884 lastPos = input.find_first_not_of(delimiters, pos);
885 // Find next "non-delimiter"
886 pos = input.find_first_of(delimiters, lastPos);