]> cygwin.com Git - cygwin-apps/setup.git/blob - String++.cc
Various warning/header cleanups necessary for clean gcc 4.3 build.
[cygwin-apps/setup.git] / String++.cc
1 /*
2 * Copyright 2005-2006, Various Contributors.
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 * A copy of the GNU General Public License can be found at
10 * http://www.gnu.org/
11 */
12
13 #include "String++.h"
14 #include <string.h>
15 #include <sstream>
16 #include <algorithm>
17
18 char *
19 new_cstr_char_array (const std::string &s)
20 {
21 size_t len = s.size();
22 char *buf = new char[len + 1];
23 if (len)
24 memcpy(buf, s.c_str(), len);
25 buf[len] = 0;
26 return buf;
27 }
28
29 std::string
30 format_1000s (int num, char sep)
31 {
32 int mult = 1;
33 while (mult * 1000 < num)
34 mult *= 1000;
35 std::ostringstream os;
36 os << ((num / mult) % 1000);
37 for (mult /= 1000; mult > 0; mult /= 1000)
38 {
39 int triplet = (num / mult) % 1000;
40 os << sep;
41 if (triplet < 100) os << '0';
42 if (triplet < 10) os << '0';
43 os << triplet;
44 }
45 return os.str();
46 }
47
48 std::string
49 stringify (int num)
50 {
51 std::ostringstream os;
52 os << num;
53 return os.str();
54 }
55
56 int
57 casecompare (const std::string& a, const std::string& b, size_t limit)
58 {
59 size_t length_to_check = std::min(a.length(), b.length());
60 if (limit && length_to_check > limit)
61 length_to_check = limit;
62
63 size_t i;
64 for (i = 0; i < length_to_check; ++i)
65 if (toupper(a[i]) < toupper(b[i]))
66 return -1;
67 else if (toupper(a[i]) > toupper(b[i]))
68 return 1;
69
70 // Hit the comparison limit without finding a difference
71 if (limit && i == limit)
72 return 0;
73
74 if (a.length() < b.length())
75 return -1;
76 else if (a.length() > b.length())
77 return 1;
78
79 return 0;
80 }
81
82 std::string
83 replace(const std::string& haystack, const std::string& needle,
84 const std::string& replacement)
85 {
86 std::string rv(haystack);
87 size_t n_len = needle.length(), r_len = replacement.length(),
88 search_start = 0;
89
90 while (true)
91 {
92 size_t pos = rv.find(needle, search_start);
93 if (pos == std::string::npos)
94 return rv;
95 rv.replace(pos, n_len, replacement);
96 search_start = pos + r_len;
97 }
98 }
This page took 0.039753 seconds and 6 git commands to generate.