song list: get rid of boost::zip_iterator and improve {Const,}SongIterator
[ncmpcpp.git] / src / utility / string.cpp
blob985b2d33dc6c765c5be02c8576edf28e3215060f
1 /***************************************************************************
2 * Copyright (C) 2008-2016 by Andrzej Rybczak *
3 * electricityispower@gmail.com *
4 * *
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 of the License, or *
8 * (at your option) any later version. *
9 * *
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. *
14 * *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. *
19 ***************************************************************************/
21 #include <cassert>
22 #include <cwctype>
23 #include <algorithm>
24 #include "utility/string.h"
26 std::string getBasename(const std::string &path)
28 size_t slash = path.rfind("/");
29 if (slash == std::string::npos)
30 return path;
31 else
32 return path.substr(slash+1);
35 std::string getParentDirectory(std::string path)
37 size_t slash = path.rfind('/');
38 if (slash == std::string::npos)
39 path = "";
40 else
41 path.resize(slash);
42 return path;
45 std::string getSharedDirectory(const std::string &dir1, const std::string &dir2)
47 size_t i = 0;
48 size_t min_len = std::min(dir1.length(), dir2.length());
49 while (i < min_len && !dir1.compare(i, 1, dir2, i, 1))
50 ++i;
51 i = dir1.rfind("/", i);
52 if (i == std::string::npos)
53 return "/";
54 else
55 return dir1.substr(0, i);
58 std::string getEnclosedString(const std::string &s, char a, char b, size_t *pos)
60 std::string result;
61 size_t i = s.find(a, pos ? *pos : 0);
62 if (i != std::string::npos)
64 ++i;
65 while (i < s.length() && s[i] != b)
67 if (s[i] == '\\' && i+1 < s.length() && (s[i+1] == '\\' || s[i+1] == b))
68 result += s[++i];
69 else
70 result += s[i];
71 ++i;
73 // we want to set pos to char after b if possible
74 if (i < s.length())
75 ++i;
76 else // we reached end of string and didn't encounter closing char
77 result.clear();
79 if (pos != 0)
80 *pos = i;
81 return result;
84 void removeInvalidCharsFromFilename(std::string &filename, bool win32_compatible)
86 const char *unallowed_chars = win32_compatible ? "\"*/:<>?\\|" : "/";
87 for (const char *c = unallowed_chars; *c; ++c)
89 for (size_t i = 0; i < filename.length(); ++i)
91 if (filename[i] == *c)
93 filename.erase(filename.begin()+i);
94 --i;