libyui-ncurses  2.44.1
 All Classes Functions Variables
stringutil.cc
1 /*
2  Copyright (C) 2000-2012 Novell, Inc
3  This library is free software; you can redistribute it and/or modify
4  it under the terms of the GNU Lesser General Public License as
5  published by the Free Software Foundation; either version 2.1 of the
6  License, or (at your option) version 3.0 of the License. This library
7  is distributed in the hope that it will be useful, but WITHOUT ANY
8  WARRANTY; without even the implied warranty of MERCHANTABILITY or
9  FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
10  License for more details. You should have received a copy of the GNU
11  Lesser General Public License along with this library; if not, write
12  to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
13  Floor, Boston, MA 02110-1301 USA
14 */
15 
16 
17 /*-/
18 
19  File: stringutil.h
20 
21  Author: Michael Andres <ma@suse.de>
22 
23 /-*/
24 
25 #include <ostream>
26 #include "stringutil.h"
27 #include "NCstring.h"
28 
29 
30 unsigned strutil::split( const std::string line_tv,
31  std::vector<std::string> & words_Vtr,
32  const std::string sep_tv,
33  const bool singlesep_bv )
34 {
35  words_Vtr.clear();
36 
37  if ( line_tv.empty() )
38  return words_Vtr.size();
39 
40  struct sepctrl
41  {
42  const std::string & sep_t;
43  sepctrl( const std::string & sep_tv ) : sep_t( sep_tv ) {}
44 
45  // Note that '\0' ist neither Sep nor NonSep
46  inline bool isSep( const char c ) const { return( sep_t.find( c ) != std::string::npos ); }
47 
48  inline bool isNonSep( const char c ) const { return( c && !isSep( c ) ); }
49 
50  inline void skipSep( const char *& p ) const { while ( isSep( *p ) ) ++p; }
51 
52  inline void skipNonSep( const char *& p ) const { while ( isNonSep( *p ) ) ++p; }
53  };
54 
55  sepctrl sep_Ci( sep_tv );
56 
57  const char * s_pci = line_tv.c_str();
58 
59  const char * c_pci = s_pci;
60 
61  // Start with c_pci at the beginning of the 1st field to add.
62  // In singlesep the beginning might be equal to the next sep,
63  // which makes an empty field before the sep.
64  if ( !singlesep_bv && sep_Ci.isSep( *c_pci ) )
65  {
66  sep_Ci.skipSep( c_pci );
67  }
68 
69  for ( s_pci = c_pci; *s_pci; s_pci = c_pci )
70  {
71  sep_Ci.skipNonSep( c_pci );
72  words_Vtr.push_back( std::string( s_pci, c_pci - s_pci ) );
73 
74  if ( *c_pci )
75  {
76  if ( singlesep_bv )
77  {
78  if ( !*( ++c_pci ) )
79  {
80  // line ends with a sep -> add the empty field behind
81  words_Vtr.push_back( "" );
82  }
83  }
84  else
85  sep_Ci.skipSep( c_pci );
86  }
87  }
88 
89  return words_Vtr.size();
90 }
91 
92 namespace std
93 {
94  ostream & operator<<( ostream & stream, const wstring & text )
95  {
96  string utf8text;
97  NCstring::RecodeFromWchar( text, "UTF-8", &utf8text );
98 
99  return stream << utf8text;
100  }
101 }