the endless quest to plug memory leaks -- episode 379
[ardour.git] / libs / pbd / strsplit.cc
1 /*
2     Copyright (C) 2000-2007 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "pbd/strsplit.h"
21
22 using namespace std;
23 using namespace Glib;
24
25 void
26 split (string str, vector<string>& result, char splitchar)
27 {
28         string::size_type pos;
29         string remaining;
30         string::size_type len = str.length();
31         int cnt;
32
33         cnt = 0;
34
35         if (str.empty()) {
36                 return;
37         }
38
39         for (string::size_type n = 0; n < len; ++n) {
40                 if (str[n] == splitchar) {
41                         cnt++;
42                 }
43         }
44
45         if (cnt == 0) {
46                 result.push_back (str);
47                 return;
48         }
49
50         remaining = str;
51
52         while ((pos = remaining.find_first_of (splitchar)) != string::npos) {
53                 if (pos != 0) {
54                         result.push_back (remaining.substr (0, pos));
55                 }
56                 remaining = remaining.substr (pos+1);
57         }
58
59         if (remaining.length()) {
60
61                 result.push_back (remaining);
62         }
63 }
64
65 void
66 split (ustring str, vector<ustring>& result, char splitchar)
67 {
68         ustring::size_type pos;
69         ustring remaining;
70         ustring::size_type len = str.length();
71         int cnt;
72
73         cnt = 0;
74
75         if (str.empty()) {
76                 return;
77         }
78
79         for (ustring::size_type n = 0; n < len; ++n) {
80                 if (str[n] == gunichar(splitchar)) {
81                         cnt++;
82                 }
83         }
84
85         if (cnt == 0) {
86                 result.push_back (str);
87                 return;
88         }
89
90         remaining = str;
91
92         while ((pos = remaining.find_first_of (splitchar)) != ustring::npos) {
93                 result.push_back (remaining.substr (0, pos));
94                 remaining = remaining.substr (pos+1);
95         }
96
97         if (remaining.length()) {
98
99                 result.push_back (remaining);
100         }
101 }