-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_thousands_separator.cpp
112 lines (91 loc) · 2.54 KB
/
string_thousands_separator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* -*- Mode: C++; indent-tabs-mode: nil; tab-width: 4 -*-
* -*- coding: utf-8 -*-
*
* Copyright (C) 2017 ~ 2018 Rekols
*
* Author: Rekols <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <cctype>
#include <regex>
#include <list>
inline std::string format_thousands_sep(const std::string &str)
{
std::string result = str;
int start_position = 0;
if (start_position >= 0) {
int end_position = result.find('.');
if (end_position < 0) {
end_position = result.length();
}
for (int i = end_position - 3; i >= start_position + 1; i -= 3) {
result.insert(i, ",");
}
}
return result;;
}
inline bool string_is_diagit(const std::string &str)
{
bool is_digit = true;
for (const char &ch : str) {
if (!isdigit(ch) && ch != '.') {
is_digit = false;
break;
}
}
return is_digit;
}
inline std::string reformat(const std::string &str)
{
std::string expression = str;
std::string seg;
std::list<std::string> exp_list;
for (int i = 0; i < expression.length(); ++i) {
const char ch = expression.at(i);
if (isdigit(ch) || ch == '.') {
seg.push_back(ch);
} else {
exp_list.push_back(seg);
seg.clear();
seg.push_back(ch);
exp_list.push_back(seg);
seg.clear();
}
if (i == expression.length() - 1) {
exp_list.push_back(seg);
}
}
std::string format_str;
for (std::string exp : exp_list) {
if (string_is_diagit(exp)) {
exp = format_thousands_sep(exp);
}
format_str += exp;
}
return format_str;
}
int main(int argc, char *argv[])
{
while (1) {
std::string str;
std::cin >> str;
if (str == "q") {
break;
}
std::cout << reformat(str) << std::endl;
}
return 0;
}