3 // Written by Bernie Bright, started 1998
5 // Copyright (C) 1998 Bernie Bright - bbright@bigpond.net.au
7 // This library is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU Library General Public
9 // License as published by the Free Software Foundation; either
10 // version 2 of the License, or (at your option) any later version.
12 // This library is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // Library General Public License for more details.
17 // You should have received a copy of the GNU Library General Public
18 // License along with this library; if not, write to the
19 // Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 // Boston, MA 02111-1307, USA.
25 #include "strutils.hxx"
34 split_whitespace( const string& str, int maxsplit )
36 vector<string> result;
37 string::size_type len = str.length();
38 string::size_type i = 0;
44 while (i < len && isspace(str[i]))
51 while (i < len && !isspace(str[i]))
58 result.push_back( str.substr(j, i-j) );
60 while (i < len && isspace(str[i]))
65 if (maxsplit && (countsplit >= maxsplit) && i < len)
67 result.push_back( str.substr( i, len-i ) );
80 split( const string& str, const char* sep, int maxsplit )
83 return split_whitespace( str, maxsplit );
85 vector<string> result;
86 int n = strlen( sep );
89 // Error: empty separator string
92 const char* s = str.c_str();
93 string::size_type len = str.length();
94 string::size_type i = 0;
95 string::size_type j = 0;
100 if (s[i] == sep[0] && (n == 1 || memcmp(s+i, sep, n) == 0))
102 result.push_back( str.substr(j,i-j) );
105 if (maxsplit && (splitcount >= maxsplit))
114 result.push_back( str.substr(j,len-j) );
119 * The lstrip(), rstrip() and strip() functions are implemented
120 * in do_strip() which uses an additional parameter to indicate what
121 * type of strip should occur.
123 const int LEFTSTRIP = 0;
124 const int RIGHTSTRIP = 1;
125 const int BOTHSTRIP = 2;
128 do_strip( const string& s, int striptype )
133 string::size_type len = s.length();
134 string::size_type i = 0;
135 if (striptype != RIGHTSTRIP)
137 while (i < len && isspace(s[i]))
143 string::size_type j = len;
144 if (striptype != LEFTSTRIP)
150 while (j >= 1 && isspace(s[j]));
154 if (i == 0 && j == len)
160 return s.substr( i, j - i );
165 lstrip( const string& s )
167 return do_strip( s, LEFTSTRIP );
171 rstrip( const string& s )
173 return do_strip( s, RIGHTSTRIP );
177 strip( const string& s )
179 return do_strip( s, BOTHSTRIP );
182 } // end namespace strutils
183 } // end namespace simgear