hx3d  1
2D/3D Simple Game Framework
string.cpp
1 /*
2  String helper functions.
3  Copyright (C) 2015 Denis BOURGE
4 
5  This library is free software; you can redistribute it and/or
6  modify it under the terms of the GNU Lesser General Public
7  License as published by the Free Software Foundation; either
8  version 2.1 of the License, or (at your option) any later version.
9 
10  This library 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 GNU
13  Lesser General Public License for more details.
14 
15  You should have received a copy of the GNU Lesser General Public
16  License along with this library; if not, write to the Free Software
17  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
18  USA
19 */
20 
21 #include "hx3d/utils/string.hpp"
22 
23 #include <sstream>
24 
25 namespace hx3d {
26 
27 std::string format(const std::string fmt, ...) {
28 
29  int size = ((int)fmt.size()) * 2 + 65536; // Use a rubric appropriate for your code
30  std::string str;
31  va_list ap;
32  while (1) { // Maximum two passes on a POSIX system...
33  str.resize(size);
34  va_start(ap, fmt);
35  int n = vsnprintf((char *)str.data(), size, fmt.c_str(), ap);
36  va_end(ap);
37  if (n > -1 && n < size) { // Everything worked
38  str.resize(n);
39  return str;
40  }
41  if (n > -1) // Needed size returned
42  size = n + 1; // For null char
43  else
44  size *= 2; // Guess at a larger size (OS specific)
45  }
46 
47  return str;
48 }
49 
50 std::string format(const std::string fmt, va_list args) {
51 
52  int size = ((int)fmt.size()) * 2 + 65536; // Use a rubric appropriate for your code
53  std::string str;
54  while (1) { // Maximum two passes on a POSIX system...
55  str.resize(size);
56  int n = vsnprintf((char *)str.data(), size, fmt.c_str(), args);
57  if (n > -1 && n < size) { // Everything worked
58  str.resize(n);
59  return str;
60  }
61  if (n > -1) // Needed size returned
62  size = n + 1; // For null char
63  else
64  size *= 2; // Guess at a larger size (OS specific)
65  }
66 
67  return str;
68 }
69 
70 std::vector<std::string>& split(const std::string &s, char delim, std::vector<std::string> &elems) {
71  std::stringstream ss(s);
72  std::string item;
73  while (std::getline(ss, item, delim)) {
74  elems.push_back(item);
75  }
76  return elems;
77 }
78 
79 
80 std::vector<std::string> split(const std::string &s, char delim) {
81  std::vector<std::string> elems;
82  split(s, delim, elems);
83  return elems;
84 }
85 
86 } /* hx3d */
std::string format(const std::string fmt,...)
Format a string using printf notation.
Definition: string.cpp:27
hx3d framework namespace
Definition: audio.hpp:26
std::vector< std::string > & split(const std::string &s, char delim, std::vector< std::string > &elems)
Split a string using a delimiter and a container.
Definition: string.cpp:70