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 char c2; // we need only one char outside the loop
131 const char c1 = *s1++; // const local variable should help compiler to optimize
133 if (c1 != c2 && ::tolower(c1) != ::tolower(c2)) // This includes the possibility that one of the characters is the null-terminator, which implies a string mismatch.
135 } while (c2 != '\0'); // At this point, we know c1 == c2, so there's no need to test them both.
139 string StringUtils::Left(const string &str, size_t count)
141 count = max((size_t)0, min(count, str.size()));
142 return str.substr(0, count);
145 string StringUtils::Mid(const string &str, size_t first, size_t count /* = string::npos */)
147 if (first + count > str.size())
148 count = str.size() - first;
150 if (first > str.size())
153 ASSERT(first + count <= str.size());
155 return str.substr(first, count);
158 string StringUtils::Right(const string &str, size_t count)
160 count = max((size_t)0, min(count, str.size()));
161 return str.substr(str.size() - count);
164 std::string& StringUtils::Trim(std::string &str)
167 return TrimRight(str);
170 // hack to ensure that std::string::iterator will be dereferenced as _unsigned_ char
171 // without this hack "TrimX" functions failed on Win32 with UTF-8 strings
172 static int isspace_c(char c)
174 return ::isspace((unsigned char)c);
177 std::string& StringUtils::TrimLeft(std::string &str)
179 str.erase(str.begin(), ::find_if(str.begin(), str.end(), ::not1(::ptr_fun(isspace_c))));
183 std::string& StringUtils::TrimRight(std::string &str)
185 str.erase(::find_if(str.rbegin(), str.rend(), ::not1(::ptr_fun(isspace_c))).base(), str.end());
189 std::string& StringUtils::RemoveDuplicatedSpacesAndTabs(std::string& str)
191 std::string::iterator it = str.begin();
192 bool onSpace = false;
193 while(it != str.end())
216 int StringUtils::Replace(string &str, char oldChar, char newChar)
218 int replacedChars = 0;
219 for (string::iterator it = str.begin(); it != str.end(); it++)
228 return replacedChars;
231 int StringUtils::Replace(std::string &str, const std::string &oldStr, const std::string &newStr)
236 int replacedChars = 0;
239 while (index < str.size() && (index = str.find(oldStr, index)) != string::npos)
241 str.replace(index, oldStr.size(), newStr);
242 index += newStr.size();
246 return replacedChars;
249 bool StringUtils::StartsWith(const std::string &str1, const std::string &str2)
251 return str1.compare(0, str2.size(), str2) == 0;
254 bool StringUtils::StartsWith(const std::string &str1, const char *s2)
256 return StartsWith(str1.c_str(), s2);
259 bool StringUtils::StartsWith(const char *s1, const char *s2)
271 bool StringUtils::StartsWithNoCase(const std::string &str1, const std::string &str2)
273 return StartsWithNoCase(str1.c_str(), str2.c_str());
276 bool StringUtils::StartsWithNoCase(const std::string &str1, const char *s2)
278 return StartsWithNoCase(str1.c_str(), s2);
281 bool StringUtils::StartsWithNoCase(const char *s1, const char *s2)
285 if (::tolower(*s1) != ::tolower(*s2))
293 bool StringUtils::EndsWith(const std::string &str1, const std::string &str2)
295 if (str1.size() < str2.size())
297 return str1.compare(str1.size() - str2.size(), str2.size(), str2) == 0;
300 bool StringUtils::EndsWith(const std::string &str1, const char *s2)
302 size_t len2 = strlen(s2);
303 if (str1.size() < len2)
305 return str1.compare(str1.size() - len2, len2, s2) == 0;
308 bool StringUtils::EndsWithNoCase(const std::string &str1, const std::string &str2)
310 if (str1.size() < str2.size())
312 const char *s1 = str1.c_str() + str1.size() - str2.size();
313 const char *s2 = str2.c_str();
316 if (::tolower(*s1) != ::tolower(*s2))
324 bool StringUtils::EndsWithNoCase(const std::string &str1, const char *s2)
326 size_t len2 = strlen(s2);
327 if (str1.size() < len2)
329 const char *s1 = str1.c_str() + str1.size() - len2;
332 if (::tolower(*s1) != ::tolower(*s2))
340 void StringUtils::JoinString(const CStdStringArray &strings, const CStdString& delimiter, CStdString& result)
343 for(CStdStringArray::const_iterator it = strings.begin(); it != strings.end(); it++ )
344 result += (*it) + delimiter;
347 result.Delete(result.size()-delimiter.size(), delimiter.size());
350 CStdString StringUtils::JoinString(const CStdStringArray &strings, const CStdString& delimiter)
353 JoinString(strings, delimiter, result);
357 CStdString StringUtils::Join(const vector<string> &strings, const CStdString& delimiter)
359 CStdStringArray strArray;
360 for (unsigned int index = 0; index < strings.size(); index++)
361 strArray.push_back(strings.at(index));
363 return JoinString(strArray, delimiter);
366 // Splits the string input into pieces delimited by delimiter.
367 // if 2 delimiters are in a row, it will include the empty string between them.
368 // added MaxStrings parameter to restrict the number of returned substrings (like perl and python)
369 int StringUtils::SplitString(const CStdString& input, const CStdString& delimiter, CStdStringArray &results, unsigned int iMaxStrings /* = 0 */)
373 int sizeS2 = delimiter.GetLength();
374 int isize = input.GetLength();
378 vector<unsigned int> positions;
380 newPos = input.Find (delimiter, 0);
384 results.push_back(input);
388 while ( newPos > iPos )
390 positions.push_back(newPos);
392 newPos = input.Find (delimiter, iPos + sizeS2);
395 // numFound is the number of delimiters which is one less
396 // than the number of substrings
397 unsigned int numFound = positions.size();
398 if (iMaxStrings > 0 && numFound >= iMaxStrings)
399 numFound = iMaxStrings - 1;
401 for ( unsigned int i = 0; i <= numFound; i++ )
409 s = input.Mid( i, positions[i] );
413 int offset = positions[i - 1] + sizeS2;
414 if ( offset < isize )
417 s = input.Mid(offset);
419 s = input.Mid( positions[i - 1] + sizeS2,
420 positions[i] - positions[i - 1] - sizeS2 );
423 results.push_back(s);
425 // return the number of substrings
426 return results.size();
429 CStdStringArray StringUtils::SplitString(const CStdString& input, const CStdString& delimiter, unsigned int iMaxStrings /* = 0 */)
431 CStdStringArray result;
432 SplitString(input, delimiter, result, iMaxStrings);
436 vector<string> StringUtils::Split(const std::string& input, const std::string& delimiter, unsigned int iMaxStrings /* = 0 */)
438 CStdStringArray result;
439 SplitString(input, delimiter, result, iMaxStrings);
441 vector<string> strArray;
442 for (unsigned int index = 0; index < result.size(); index++)
443 strArray.push_back(result.at(index));
448 // returns the number of occurrences of strFind in strInput.
449 int StringUtils::FindNumber(const CStdString& strInput, const CStdString &strFind)
451 int pos = strInput.Find(strFind, 0);
456 pos = strInput.Find(strFind, pos + 1);
461 // Compares separately the numeric and alphabetic parts of a string.
462 // returns negative if left < right, positive if left > right
463 // and 0 if they are identical (essentially calculates left - right)
464 int64_t StringUtils::AlphaNumericCompare(const wchar_t *left, const wchar_t *right)
466 wchar_t *l = (wchar_t *)left;
467 wchar_t *r = (wchar_t *)right;
471 const collate<wchar_t>& coll = use_facet< collate<wchar_t> >( locale() );
473 while (*l != 0 && *r != 0)
475 // check if we have a numerical value
476 if (*l >= L'0' && *l <= L'9' && *r >= L'0' && *r <= L'9')
480 while (*ld >= L'0' && *ld <= L'9' && ld < l + 15)
481 { // compare only up to 15 digits
487 while (*rd >= L'0' && *rd <= L'9' && rd < r + 15)
488 { // compare only up to 15 digits
490 rnum += *rd++ - L'0';
492 // do we have numbers?
494 { // yes - and they're different!
501 // do case less comparison
503 if (lc >= L'A' && lc <= L'Z')
506 if (rc >= L'A' && rc <= L'Z')
509 // ok, do a normal comparison, taking current locale into account. Add special case stuff (eg '(' characters)) in here later
510 if ((cmp_res = coll.compare(&lc, &lc + 1, &rc, &rc + 1)) != 0)
524 return 0; // files are the same
527 int StringUtils::DateStringToYYYYMMDD(const CStdString &dateString)
529 CStdStringArray days;
530 int splitCount = StringUtils::SplitString(dateString, "-", days);
532 return atoi(days[0].c_str());
533 else if (splitCount == 2)
534 return atoi(days[0].c_str())*100+atoi(days[1].c_str());
535 else if (splitCount == 3)
536 return atoi(days[0].c_str())*10000+atoi(days[1].c_str())*100+atoi(days[2].c_str());
541 long StringUtils::TimeStringToSeconds(const CStdString &timeString)
543 CStdString strCopy(timeString);
544 strCopy.TrimLeft(" \n\r\t");
545 strCopy.TrimRight(" \n\r\t");
546 if(StringUtils::EndsWithNoCase(strCopy, " min"))
548 // this is imdb format of "XXX min"
549 return 60 * atoi(strCopy.c_str());
553 CStdStringArray secs;
554 StringUtils::SplitString(strCopy, ":", secs);
556 for (unsigned int i = 0; i < 3 && i < secs.size(); i++)
559 timeInSecs += atoi(secs[i]);
565 CStdString StringUtils::SecondsToTimeString(long lSeconds, TIME_FORMAT format)
567 int hh = lSeconds / 3600;
568 lSeconds = lSeconds % 3600;
569 int mm = lSeconds / 60;
570 int ss = lSeconds % 60;
572 if (format == TIME_FORMAT_GUESS)
573 format = (hh >= 1) ? TIME_FORMAT_HH_MM_SS : TIME_FORMAT_MM_SS;
575 if (format & TIME_FORMAT_HH)
576 strHMS.AppendFormat("%02.2i", hh);
577 else if (format & TIME_FORMAT_H)
578 strHMS.AppendFormat("%i", hh);
579 if (format & TIME_FORMAT_MM)
580 strHMS.AppendFormat(strHMS.IsEmpty() ? "%02.2i" : ":%02.2i", mm);
581 if (format & TIME_FORMAT_SS)
582 strHMS.AppendFormat(strHMS.IsEmpty() ? "%02.2i" : ":%02.2i", ss);
586 bool StringUtils::IsNaturalNumber(const CStdString& str)
589 // allow whitespace,digits,whitespace
590 while (i < str.size() && isspace((unsigned char) str[i]))
592 while (i < str.size() && isdigit((unsigned char) str[i]))
596 while (i < str.size() && isspace((unsigned char) str[i]))
598 return i == str.size() && n > 0;
601 bool StringUtils::IsInteger(const CStdString& str)
604 // allow whitespace,-,digits,whitespace
605 while (i < str.size() && isspace((unsigned char) str[i]))
607 if (i < str.size() && str[i] == '-')
609 while (i < str.size() && isdigit((unsigned char) str[i]))
613 while (i < str.size() && isspace((unsigned char) str[i]))
615 return i == str.size() && n > 0;
618 void StringUtils::RemoveCRLF(CStdString& strLine)
620 while ( strLine.size() && (strLine.Right(1) == "\n" || strLine.Right(1) == "\r") )
622 strLine = strLine.Left(std::max(0, (int)strLine.size() - 1));
626 CStdString StringUtils::SizeToString(int64_t size)
629 const char prefixes[] = {' ','k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'};
631 double s = (double)size;
632 while (i < sizeof(prefixes)/sizeof(prefixes[0]) && s >= 1000.0)
639 strLabel.Format("%.0lf %cB ", s, prefixes[i]);
641 strLabel.Format("%.1lf %cB", s, prefixes[i]);
643 strLabel.Format("%.2lf %cB", s, prefixes[i]);
648 // return -1 if not, else return the utf8 char length.
649 int IsUTF8Letter(const unsigned char *str)
652 // unicode -> utf8 table: http://www.utf8-chartable.de/
653 // latin characters in unicode: http://en.wikipedia.org/wiki/Latin_characters_in_Unicode
654 unsigned char ch = str[0];
657 if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
661 unsigned char ch2 = str[1];
664 // check latin 1 letter table: http://en.wikipedia.org/wiki/C1_Controls_and_Latin-1_Supplement
665 if (ch == 0xC3 && ch2 >= 0x80 && ch2 <= 0xBF && ch2 != 0x97 && ch2 != 0xB7)
667 // check latin extended A table: http://en.wikipedia.org/wiki/Latin_Extended-A
668 if (ch >= 0xC4 && ch <= 0xC7 && ch2 >= 0x80 && ch2 <= 0xBF)
670 // check latin extended B table: http://en.wikipedia.org/wiki/Latin_Extended-B
671 // and International Phonetic Alphabet: http://en.wikipedia.org/wiki/IPA_Extensions_(Unicode_block)
672 if (((ch == 0xC8 || ch == 0xC9) && ch2 >= 0x80 && ch2 <= 0xBF)
673 || (ch == 0xCA && ch2 >= 0x80 && ch2 <= 0xAF))
678 size_t StringUtils::FindWords(const char *str, const char *wordLowerCase)
680 // NOTE: This assumes word is lowercase!
681 unsigned char *s = (unsigned char *)str;
684 // start with a compare
685 unsigned char *c = s;
686 unsigned char *w = (unsigned char *)wordLowerCase;
688 while (same && *c && *w)
690 unsigned char lc = *c++;
691 if (lc >= 'A' && lc <= 'Z')
694 if (lc != *w++) // different
697 if (same && *w == 0) // only the same if word has been exhausted
698 return (const char *)s - str;
700 // otherwise, skip current word (composed by latin letters) or number
702 if (*s >= '0' && *s <= '9')
705 while (*s >= '0' && *s <= '9') ++s;
707 else if ((l = IsUTF8Letter(s)) > 0)
710 while ((l = IsUTF8Letter(s)) > 0) s += l;
714 while (*s && *s == ' ') s++;
716 // and repeat until we're done
719 return CStdString::npos;
722 // assumes it is called from after the first open bracket is found
723 int StringUtils::FindEndBracket(const CStdString &str, char opener, char closer, int startPos)
726 for (unsigned int i = startPos; i < str.size(); i++)
728 if (str[i] == opener)
730 else if (str[i] == closer)
738 return (int)CStdString::npos;
741 void StringUtils::WordToDigits(CStdString &word)
743 static const char word_to_letter[] = "22233344455566677778889999";
745 for (unsigned int i = 0; i < word.size(); ++i)
746 { // NB: This assumes ascii, which probably needs extending at some point.
747 char letter = word[i];
748 if ((letter >= 'a' && letter <= 'z')) // assume contiguous letter range
750 word[i] = word_to_letter[letter-'a'];
752 else if (letter < '0' || letter > '9') // We want to keep 0-9!
754 word[i] = ' '; // replace everything else with a space
759 CStdString StringUtils::CreateUUID()
761 /* This function generate a DCE 1.1, ISO/IEC 11578:1996 and IETF RFC-4122
762 * Version 4 conform local unique UUID based upon random number generation.
765 char *pUuidStr = UuidStrTmp;
768 static bool m_uuidInitialized = false;
769 if (!m_uuidInitialized)
771 /* use current time as the seed for rand()*/
773 m_uuidInitialized = true;
776 /*Data1 - 8 characters.*/
777 for(i = 0; i < 8; i++, pUuidStr++)
778 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
780 /*Data2 - 4 characters.*/
782 for(i = 0; i < 4; i++, pUuidStr++)
783 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
785 /*Data3 - 4 characters.*/
787 for(i = 0; i < 4; i++, pUuidStr++)
788 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
790 /*Data4 - 4 characters.*/
792 for(i = 0; i < 4; i++, pUuidStr++)
793 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
795 /*Data5 - 12 characters.*/
797 for(i = 0; i < 12; i++, pUuidStr++)
798 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
802 m_lastUUID = UuidStrTmp;
806 bool StringUtils::ValidateUUID(const CStdString &uuid)
809 guidRE.RegComp(ADDON_GUID_RE);
810 return (guidRE.RegFind(uuid.c_str()) == 0);
813 double StringUtils::CompareFuzzy(const CStdString &left, const CStdString &right)
815 return (0.5 + fstrcmp(left.c_str(), right.c_str(), 0.0) * (left.length() + right.length())) / 2.0;
818 int StringUtils::FindBestMatch(const CStdString &str, const CStdStringArray &strings, double &matchscore)
824 for (CStdStringArray::const_iterator it = strings.begin(); it != strings.end(); it++, i++)
826 int maxlength = max(str.length(), it->length());
827 double score = StringUtils::CompareFuzzy(str, *it) / maxlength;
828 if (score > matchscore)
837 bool StringUtils::ContainsKeyword(const CStdString &str, const CStdStringArray &keywords)
839 for (CStdStringArray::const_iterator it = keywords.begin(); it != keywords.end(); it++)
841 if (str.find(*it) != str.npos)
847 size_t StringUtils::utf8_strlen(const char *s)
852 if ((*s++ & 0xC0) != 0x80)
858 std::string StringUtils::Paramify(const std::string ¶m)
860 std::string result = param;
862 StringUtils::Replace(result, "\\", "\\\\");
863 // escape double quotes
864 StringUtils::Replace(result, "\"", "\\\"");
866 // add double quotes around the whole string
867 return "\"" + result + "\"";
870 void StringUtils::Tokenize(const std::string& input, std::vector<std::string>& tokens, const std::string& delimiters)
872 // Tokenize ripped from http://www.linuxselfhelp.com/HOWTO/C++Programming-HOWTO-7.html
873 // Skip delimiters at beginning.
874 string::size_type lastPos = input.find_first_not_of(delimiters, 0);
875 // Find first "non-delimiter".
876 string::size_type pos = input.find_first_of(delimiters, lastPos);
878 while (string::npos != pos || string::npos != lastPos)
880 // Found a token, add it to the vector.
881 tokens.push_back(input.substr(lastPos, pos - lastPos));
882 // Skip delimiters. Note the "not_of"
883 lastPos = input.find_first_not_of(delimiters, pos);
884 // Find next "non-delimiter"
885 pos = input.find_first_of(delimiters, lastPos);