utils.cpp
Go to the documentation of this file.
1 #include "utils.hpp"
2 
3 #include <sstream>
4 
5 namespace iv
6 {
7 
8 size_t utf8_size( std::string const & val )
9 {
10  return utf8_size( val.c_str() );
11 }
12 
13 size_t utf8_size( const char * val )
14 {
15  size_t res = 0;
16  for( size_t i = 0; val[ i ]; i++ )
17  {
18  char c = val[ i ];
19  if( ( c & 0b11000000 ) == 0b10000000 ) // non-first bytes in utf8 begin with 0b10
20  continue;
21  res++;
22  }
23 
24  return res;
25 }
26 
27 bool utf8_is_first_byte( char c )
28 {
29  return ( c & 0b11000000 ) != 0b10000000;
30 }
31 
32 void string_explode( std::string const & s, char delim, std::vector< std::string > & result )
33 {
34  std::istringstream iss(s);
35  for (std::string token; std::getline(iss, token, delim); )
36  result.push_back(std::move(token));
37  if( result.empty() )
38  result.push_back( "" );
39 }
40 
41 
42 std::string string_trim( std::string const & s )
43 {
44  int left = -1;
45  int right = 0;
46 
47  for( char c : s )
48  if( c==' ' || c=='\n' || c=='\r' || c=='\t' )
49  right++;
50  else if( left<0 )
51  left = right,
52  right = 0;
53  else
54  right = 0;
55 
56  if( left<0 )
57  return std::string("");
58  else
59  return s.substr( left, s.size()-right-left );
60 }
61 
62 std::string string_ltrim( std::string const & s )
63 {
64  int left = -1;
65  int tmp = 0;
66 
67  for( char c : s )
68  if( c==' ' || c=='\n' || c=='\r' || c=='\t' )
69  tmp++;
70  else if( left<0 )
71  left = tmp;
72 
73  if( left<0 )
74  return std::string("");
75  else
76  return s.substr( left, s.size()-left );
77 }
78 
79 std::string string_rtrim( std::string const & s )
80 {
81  int right = 0;
82 
83  for( char c : s )
84  if( c==' ' || c=='\n' || c=='\r' || c=='\t' )
85  right++;
86  else
87  right = 0;
88 
89  if( size_t(right) == s.size() )
90  return std::string("");
91  else
92  return s.substr( 0, s.size()-right );
93 }
94 
95 }