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 wstring StringUtils::Format(const wchar_t *fmt, ...)
110 wstring str = FormatV(fmt, args);
116 wstring StringUtils::FormatV(const wchar_t *fmt, va_list args)
121 int size = FORMAT_BLOCK_SIZE;
124 wchar_t *cstr = reinterpret_cast<wchar_t*>(malloc(sizeof(wchar_t) * size));
130 va_copy(argCopy, args);
132 int nActual = vswprintf(cstr, size, fmt, argCopy);
135 if (nActual > -1 && nActual < size) // We got a valid result
137 wstring str(cstr, nActual);
141 if (nActual > -1) // Exactly what we will need (glibc 2.1)
143 else // Let's try to double the size (glibc 2.0)
146 wchar_t *new_cstr = reinterpret_cast<wchar_t*>(realloc(cstr, sizeof(wchar_t) * size));
147 if (new_cstr == NULL)
159 void StringUtils::ToUpper(string &str)
161 transform(str.begin(), str.end(), str.begin(), ::toupper);
164 void StringUtils::ToUpper(wstring &str)
166 transform(str.begin(), str.end(), str.begin(), ::towupper);
169 void StringUtils::ToLower(string &str)
171 transform(str.begin(), str.end(), str.begin(), ::tolower);
174 void StringUtils::ToLower(wstring &str)
176 transform(str.begin(), str.end(), str.begin(), ::towlower);
179 bool StringUtils::EqualsNoCase(const std::string &str1, const std::string &str2)
181 return EqualsNoCase(str1.c_str(), str2.c_str());
184 bool StringUtils::EqualsNoCase(const std::string &str1, const char *s2)
186 return EqualsNoCase(str1.c_str(), s2);
189 bool StringUtils::EqualsNoCase(const char *s1, const char *s2)
191 char c2; // we need only one char outside the loop
194 const char c1 = *s1++; // const local variable should help compiler to optimize
196 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.
198 } while (c2 != '\0'); // At this point, we know c1 == c2, so there's no need to test them both.
202 string StringUtils::Left(const string &str, size_t count)
204 count = max((size_t)0, min(count, str.size()));
205 return str.substr(0, count);
208 string StringUtils::Mid(const string &str, size_t first, size_t count /* = string::npos */)
210 if (first + count > str.size())
211 count = str.size() - first;
213 if (first > str.size())
216 ASSERT(first + count <= str.size());
218 return str.substr(first, count);
221 string StringUtils::Right(const string &str, size_t count)
223 count = max((size_t)0, min(count, str.size()));
224 return str.substr(str.size() - count);
227 std::string& StringUtils::Trim(std::string &str)
230 return TrimRight(str);
233 // hack to ensure that std::string::iterator will be dereferenced as _unsigned_ char
234 // without this hack "TrimX" functions failed on Win32 with UTF-8 strings
235 static int isspace_c(char c)
237 return ::isspace((unsigned char)c);
240 std::string& StringUtils::TrimLeft(std::string &str)
242 str.erase(str.begin(), ::find_if(str.begin(), str.end(), ::not1(::ptr_fun(isspace_c))));
246 std::string& StringUtils::TrimLeft(std::string &str, const std::string& chars)
248 size_t nidx = str.find_first_not_of(chars);
249 str.substr(nidx == str.npos ? 0 : nidx).swap(str);
253 std::string& StringUtils::TrimRight(std::string &str)
255 str.erase(::find_if(str.rbegin(), str.rend(), ::not1(::ptr_fun(isspace_c))).base(), str.end());
259 std::string& StringUtils::TrimRight(std::string &str, const std::string& chars)
261 size_t nidx = str.find_last_not_of(chars);
262 str.erase(str.npos == nidx ? 0 : ++nidx);
266 std::string& StringUtils::RemoveDuplicatedSpacesAndTabs(std::string& str)
268 std::string::iterator it = str.begin();
269 bool onSpace = false;
270 while(it != str.end())
293 int StringUtils::Replace(string &str, char oldChar, char newChar)
295 int replacedChars = 0;
296 for (string::iterator it = str.begin(); it != str.end(); it++)
305 return replacedChars;
308 int StringUtils::Replace(std::string &str, const std::string &oldStr, const std::string &newStr)
313 int replacedChars = 0;
316 while (index < str.size() && (index = str.find(oldStr, index)) != string::npos)
318 str.replace(index, oldStr.size(), newStr);
319 index += newStr.size();
323 return replacedChars;
326 bool StringUtils::StartsWith(const std::string &str1, const std::string &str2)
328 return str1.compare(0, str2.size(), str2) == 0;
331 bool StringUtils::StartsWith(const std::string &str1, const char *s2)
333 return StartsWith(str1.c_str(), s2);
336 bool StringUtils::StartsWith(const char *s1, const char *s2)
348 bool StringUtils::StartsWithNoCase(const std::string &str1, const std::string &str2)
350 return StartsWithNoCase(str1.c_str(), str2.c_str());
353 bool StringUtils::StartsWithNoCase(const std::string &str1, const char *s2)
355 return StartsWithNoCase(str1.c_str(), s2);
358 bool StringUtils::StartsWithNoCase(const char *s1, const char *s2)
362 if (::tolower(*s1) != ::tolower(*s2))
370 bool StringUtils::EndsWith(const std::string &str1, const std::string &str2)
372 if (str1.size() < str2.size())
374 return str1.compare(str1.size() - str2.size(), str2.size(), str2) == 0;
377 bool StringUtils::EndsWith(const std::string &str1, const char *s2)
379 size_t len2 = strlen(s2);
380 if (str1.size() < len2)
382 return str1.compare(str1.size() - len2, len2, s2) == 0;
385 bool StringUtils::EndsWithNoCase(const std::string &str1, const std::string &str2)
387 if (str1.size() < str2.size())
389 const char *s1 = str1.c_str() + str1.size() - str2.size();
390 const char *s2 = str2.c_str();
393 if (::tolower(*s1) != ::tolower(*s2))
401 bool StringUtils::EndsWithNoCase(const std::string &str1, const char *s2)
403 size_t len2 = strlen(s2);
404 if (str1.size() < len2)
406 const char *s1 = str1.c_str() + str1.size() - len2;
409 if (::tolower(*s1) != ::tolower(*s2))
417 void StringUtils::JoinString(const CStdStringArray &strings, const CStdString& delimiter, CStdString& result)
420 for(CStdStringArray::const_iterator it = strings.begin(); it != strings.end(); it++ )
421 result += (*it) + delimiter;
424 result.Delete(result.size()-delimiter.size(), delimiter.size());
427 CStdString StringUtils::JoinString(const CStdStringArray &strings, const CStdString& delimiter)
430 JoinString(strings, delimiter, result);
434 CStdString StringUtils::Join(const vector<string> &strings, const CStdString& delimiter)
436 CStdStringArray strArray;
437 for (unsigned int index = 0; index < strings.size(); index++)
438 strArray.push_back(strings.at(index));
440 return JoinString(strArray, delimiter);
443 // Splits the string input into pieces delimited by delimiter.
444 // if 2 delimiters are in a row, it will include the empty string between them.
445 // added MaxStrings parameter to restrict the number of returned substrings (like perl and python)
446 int StringUtils::SplitString(const CStdString& input, const CStdString& delimiter, CStdStringArray &results, unsigned int iMaxStrings /* = 0 */)
450 int sizeS2 = delimiter.GetLength();
451 int isize = input.GetLength();
455 vector<unsigned int> positions;
457 newPos = input.Find (delimiter, 0);
461 results.push_back(input);
465 while ( newPos > iPos )
467 positions.push_back(newPos);
469 newPos = input.Find (delimiter, iPos + sizeS2);
472 // numFound is the number of delimiters which is one less
473 // than the number of substrings
474 unsigned int numFound = positions.size();
475 if (iMaxStrings > 0 && numFound >= iMaxStrings)
476 numFound = iMaxStrings - 1;
478 for ( unsigned int i = 0; i <= numFound; i++ )
486 s = input.Mid( i, positions[i] );
490 int offset = positions[i - 1] + sizeS2;
491 if ( offset < isize )
494 s = input.Mid(offset);
496 s = input.Mid( positions[i - 1] + sizeS2,
497 positions[i] - positions[i - 1] - sizeS2 );
500 results.push_back(s);
502 // return the number of substrings
503 return results.size();
506 CStdStringArray StringUtils::SplitString(const CStdString& input, const CStdString& delimiter, unsigned int iMaxStrings /* = 0 */)
508 CStdStringArray result;
509 SplitString(input, delimiter, result, iMaxStrings);
513 vector<string> StringUtils::Split(const std::string& input, const std::string& delimiter, unsigned int iMaxStrings /* = 0 */)
515 CStdStringArray result;
516 SplitString(input, delimiter, result, iMaxStrings);
518 vector<string> strArray;
519 for (unsigned int index = 0; index < result.size(); index++)
520 strArray.push_back(result.at(index));
525 // returns the number of occurrences of strFind in strInput.
526 int StringUtils::FindNumber(const CStdString& strInput, const CStdString &strFind)
528 int pos = strInput.Find(strFind, 0);
533 pos = strInput.Find(strFind, pos + 1);
538 // Compares separately the numeric and alphabetic parts of a string.
539 // returns negative if left < right, positive if left > right
540 // and 0 if they are identical (essentially calculates left - right)
541 int64_t StringUtils::AlphaNumericCompare(const wchar_t *left, const wchar_t *right)
543 wchar_t *l = (wchar_t *)left;
544 wchar_t *r = (wchar_t *)right;
548 const collate<wchar_t>& coll = use_facet< collate<wchar_t> >( locale() );
550 while (*l != 0 && *r != 0)
552 // check if we have a numerical value
553 if (*l >= L'0' && *l <= L'9' && *r >= L'0' && *r <= L'9')
557 while (*ld >= L'0' && *ld <= L'9' && ld < l + 15)
558 { // compare only up to 15 digits
564 while (*rd >= L'0' && *rd <= L'9' && rd < r + 15)
565 { // compare only up to 15 digits
567 rnum += *rd++ - L'0';
569 // do we have numbers?
571 { // yes - and they're different!
578 // do case less comparison
580 if (lc >= L'A' && lc <= L'Z')
583 if (rc >= L'A' && rc <= L'Z')
586 // ok, do a normal comparison, taking current locale into account. Add special case stuff (eg '(' characters)) in here later
587 if ((cmp_res = coll.compare(&lc, &lc + 1, &rc, &rc + 1)) != 0)
601 return 0; // files are the same
604 int StringUtils::DateStringToYYYYMMDD(const CStdString &dateString)
606 CStdStringArray days;
607 int splitCount = StringUtils::SplitString(dateString, "-", days);
609 return atoi(days[0].c_str());
610 else if (splitCount == 2)
611 return atoi(days[0].c_str())*100+atoi(days[1].c_str());
612 else if (splitCount == 3)
613 return atoi(days[0].c_str())*10000+atoi(days[1].c_str())*100+atoi(days[2].c_str());
618 long StringUtils::TimeStringToSeconds(const CStdString &timeString)
620 CStdString strCopy(timeString);
621 StringUtils::Trim(strCopy);
622 if(StringUtils::EndsWithNoCase(strCopy, " min"))
624 // this is imdb format of "XXX min"
625 return 60 * atoi(strCopy.c_str());
629 CStdStringArray secs;
630 StringUtils::SplitString(strCopy, ":", secs);
632 for (unsigned int i = 0; i < 3 && i < secs.size(); i++)
635 timeInSecs += atoi(secs[i]);
641 CStdString StringUtils::SecondsToTimeString(long lSeconds, TIME_FORMAT format)
643 int hh = lSeconds / 3600;
644 lSeconds = lSeconds % 3600;
645 int mm = lSeconds / 60;
646 int ss = lSeconds % 60;
648 if (format == TIME_FORMAT_GUESS)
649 format = (hh >= 1) ? TIME_FORMAT_HH_MM_SS : TIME_FORMAT_MM_SS;
651 if (format & TIME_FORMAT_HH)
652 strHMS.AppendFormat("%02.2i", hh);
653 else if (format & TIME_FORMAT_H)
654 strHMS.AppendFormat("%i", hh);
655 if (format & TIME_FORMAT_MM)
656 strHMS.AppendFormat(strHMS.empty() ? "%02.2i" : ":%02.2i", mm);
657 if (format & TIME_FORMAT_SS)
658 strHMS.AppendFormat(strHMS.empty() ? "%02.2i" : ":%02.2i", ss);
662 bool StringUtils::IsNaturalNumber(const CStdString& str)
665 // allow whitespace,digits,whitespace
666 while (i < str.size() && isspace((unsigned char) str[i]))
668 while (i < str.size() && isdigit((unsigned char) str[i]))
672 while (i < str.size() && isspace((unsigned char) str[i]))
674 return i == str.size() && n > 0;
677 bool StringUtils::IsInteger(const CStdString& str)
680 // allow whitespace,-,digits,whitespace
681 while (i < str.size() && isspace((unsigned char) str[i]))
683 if (i < str.size() && str[i] == '-')
685 while (i < str.size() && isdigit((unsigned char) str[i]))
689 while (i < str.size() && isspace((unsigned char) str[i]))
691 return i == str.size() && n > 0;
694 void StringUtils::RemoveCRLF(CStdString& strLine)
696 while ( strLine.size() && (strLine.Right(1) == "\n" || strLine.Right(1) == "\r") )
698 strLine = strLine.Left(std::max(0, (int)strLine.size() - 1));
702 CStdString StringUtils::SizeToString(int64_t size)
705 const char prefixes[] = {' ','k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'};
707 double s = (double)size;
708 while (i < sizeof(prefixes)/sizeof(prefixes[0]) && s >= 1000.0)
715 strLabel = StringUtils::Format("%.0lf %cB ", s, prefixes[i]);
717 strLabel = StringUtils::Format("%.1lf %cB", s, prefixes[i]);
719 strLabel = StringUtils::Format("%.2lf %cB", s, prefixes[i]);
724 // return -1 if not, else return the utf8 char length.
725 int IsUTF8Letter(const unsigned char *str)
728 // unicode -> utf8 table: http://www.utf8-chartable.de/
729 // latin characters in unicode: http://en.wikipedia.org/wiki/Latin_characters_in_Unicode
730 unsigned char ch = str[0];
733 if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
737 unsigned char ch2 = str[1];
740 // check latin 1 letter table: http://en.wikipedia.org/wiki/C1_Controls_and_Latin-1_Supplement
741 if (ch == 0xC3 && ch2 >= 0x80 && ch2 <= 0xBF && ch2 != 0x97 && ch2 != 0xB7)
743 // check latin extended A table: http://en.wikipedia.org/wiki/Latin_Extended-A
744 if (ch >= 0xC4 && ch <= 0xC7 && ch2 >= 0x80 && ch2 <= 0xBF)
746 // check latin extended B table: http://en.wikipedia.org/wiki/Latin_Extended-B
747 // and International Phonetic Alphabet: http://en.wikipedia.org/wiki/IPA_Extensions_(Unicode_block)
748 if (((ch == 0xC8 || ch == 0xC9) && ch2 >= 0x80 && ch2 <= 0xBF)
749 || (ch == 0xCA && ch2 >= 0x80 && ch2 <= 0xAF))
754 size_t StringUtils::FindWords(const char *str, const char *wordLowerCase)
756 // NOTE: This assumes word is lowercase!
757 unsigned char *s = (unsigned char *)str;
760 // start with a compare
761 unsigned char *c = s;
762 unsigned char *w = (unsigned char *)wordLowerCase;
764 while (same && *c && *w)
766 unsigned char lc = *c++;
767 if (lc >= 'A' && lc <= 'Z')
770 if (lc != *w++) // different
773 if (same && *w == 0) // only the same if word has been exhausted
774 return (const char *)s - str;
776 // otherwise, skip current word (composed by latin letters) or number
778 if (*s >= '0' && *s <= '9')
781 while (*s >= '0' && *s <= '9') ++s;
783 else if ((l = IsUTF8Letter(s)) > 0)
786 while ((l = IsUTF8Letter(s)) > 0) s += l;
790 while (*s && *s == ' ') s++;
792 // and repeat until we're done
795 return CStdString::npos;
798 // assumes it is called from after the first open bracket is found
799 int StringUtils::FindEndBracket(const CStdString &str, char opener, char closer, int startPos)
802 for (unsigned int i = startPos; i < str.size(); i++)
804 if (str[i] == opener)
806 else if (str[i] == closer)
814 return (int)CStdString::npos;
817 void StringUtils::WordToDigits(CStdString &word)
819 static const char word_to_letter[] = "22233344455566677778889999";
820 StringUtils::ToLower(word);
821 for (unsigned int i = 0; i < word.size(); ++i)
822 { // NB: This assumes ascii, which probably needs extending at some point.
823 char letter = word[i];
824 if ((letter >= 'a' && letter <= 'z')) // assume contiguous letter range
826 word[i] = word_to_letter[letter-'a'];
828 else if (letter < '0' || letter > '9') // We want to keep 0-9!
830 word[i] = ' '; // replace everything else with a space
835 CStdString StringUtils::CreateUUID()
837 /* This function generate a DCE 1.1, ISO/IEC 11578:1996 and IETF RFC-4122
838 * Version 4 conform local unique UUID based upon random number generation.
841 char *pUuidStr = UuidStrTmp;
844 static bool m_uuidInitialized = false;
845 if (!m_uuidInitialized)
847 /* use current time as the seed for rand()*/
849 m_uuidInitialized = true;
852 /*Data1 - 8 characters.*/
853 for(i = 0; i < 8; i++, pUuidStr++)
854 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
856 /*Data2 - 4 characters.*/
858 for(i = 0; i < 4; i++, pUuidStr++)
859 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
861 /*Data3 - 4 characters.*/
863 for(i = 0; i < 4; i++, pUuidStr++)
864 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
866 /*Data4 - 4 characters.*/
868 for(i = 0; i < 4; i++, pUuidStr++)
869 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
871 /*Data5 - 12 characters.*/
873 for(i = 0; i < 12; i++, pUuidStr++)
874 ((*pUuidStr = (rand() % 16)) < 10) ? *pUuidStr += 48 : *pUuidStr += 55;
878 m_lastUUID = UuidStrTmp;
882 bool StringUtils::ValidateUUID(const CStdString &uuid)
885 guidRE.RegComp(ADDON_GUID_RE);
886 return (guidRE.RegFind(uuid.c_str()) == 0);
889 double StringUtils::CompareFuzzy(const CStdString &left, const CStdString &right)
891 return (0.5 + fstrcmp(left.c_str(), right.c_str(), 0.0) * (left.length() + right.length())) / 2.0;
894 int StringUtils::FindBestMatch(const CStdString &str, const CStdStringArray &strings, double &matchscore)
900 for (CStdStringArray::const_iterator it = strings.begin(); it != strings.end(); it++, i++)
902 int maxlength = max(str.length(), it->length());
903 double score = StringUtils::CompareFuzzy(str, *it) / maxlength;
904 if (score > matchscore)
913 bool StringUtils::ContainsKeyword(const CStdString &str, const CStdStringArray &keywords)
915 for (CStdStringArray::const_iterator it = keywords.begin(); it != keywords.end(); it++)
917 if (str.find(*it) != str.npos)
923 size_t StringUtils::utf8_strlen(const char *s)
928 if ((*s++ & 0xC0) != 0x80)
934 std::string StringUtils::Paramify(const std::string ¶m)
936 std::string result = param;
938 StringUtils::Replace(result, "\\", "\\\\");
939 // escape double quotes
940 StringUtils::Replace(result, "\"", "\\\"");
942 // add double quotes around the whole string
943 return "\"" + result + "\"";
946 void StringUtils::Tokenize(const std::string& input, std::vector<std::string>& tokens, const std::string& delimiters)
948 // Tokenize ripped from http://www.linuxselfhelp.com/HOWTO/C++Programming-HOWTO-7.html
949 // Skip delimiters at beginning.
950 string::size_type lastPos = input.find_first_not_of(delimiters, 0);
951 // Find first "non-delimiter".
952 string::size_type pos = input.find_first_of(delimiters, lastPos);
954 while (string::npos != pos || string::npos != lastPos)
956 // Found a token, add it to the vector.
957 tokens.push_back(input.substr(lastPos, pos - lastPos));
958 // Skip delimiters. Note the "not_of"
959 lastPos = input.find_first_not_of(delimiters, pos);
960 // Find next "non-delimiter"
961 pos = input.find_first_of(delimiters, lastPos);