How to add commas to a string using recursion - c++

I'm a beginner on programming. I'm coding a school assignment and its asking me to add commas to a string using recursion. I have most of it done but when I input a number greater than a million it doesn't add a comma before the first digit. This is what i have so far:
// commas - Convert a number (n) into a string, with commas
string commas(int n) {
ostringstream converted;
converted << n;
string number = converted.str();
int size = number.length();
if (size < 4 )
{
return number;
}
if (size >= 4 )
{
return number.substr(0, number.size() - 3) + "," + number.substr(number.size() - 3, number.length());
}
}
Any help would be greatly appreciated!

The algorithm is fairly simple. It is very similar to your solution except I added the part necessary for recursion. To understand how it works, remove tack_on. Here is example output:
1
10
100
These are the first groups that are returned when the terminating condition is reached (s.size() < 4). Then the rest of the groups are prefixed with a comma and "tacked on". The entire string is built using recursion. This is important because if you left number.substr(0, number.size() - 3) in, your output would look like this:
11,000
1010,000
100100,000
11,0001000,000
I use std::to_string which is C++11:
#include <iostream>
std::string addCommas(int n)
{
std::string s = std::to_string(n);
if (s.size() < 4) return s;
else
{
std::string tack_on = "," + s.substr(s.size() - 3, s.size());
return addCommas(n / 1000) + tack_on;
}
}
You only need to make minimal changes for the C++03/stringstream version:
#include <sstream>
std::ostringstream oss;
std::string addCommas(int n)
{
oss.str(""); // to avoid std::bad_alloc
oss << n;
std::string s = oss.str();
// etc
}
Testing:
int main()
{
std::cout << addCommas(1) << "\n";
std::cout << addCommas(10) << "\n";
std::cout << addCommas(100) << "\n";
std::cout << addCommas(1000) << "\n";
std::cout << addCommas(10000) << "\n";
std::cout << addCommas(100000) << "\n";
std::cout << addCommas(1000000) << "\n";
return 0;
}
Output:
1
10
100
1,000
10,000
100,000
1,000,000

I think this one is a bit simpler and easier to follow:
std::string commas(int n)
{
std::string s = std::to_string(n%1000);
if ((n/1000) == 0) return s;
else
{
// Add zeros if required
while(s.size() < 3)
{
s = "0" + s;
}
return commas(n / 1000) + "," + s;
}
}

an alternative approach without recursion:
class Grouping3 : public std::numpunct< char >
{
protected:
std::string do_grouping() const { return "\003"; }
};
std::string commas( int n )
{
std::ostringstream converted;
converted.imbue( std::locale( converted.getloc(), new Grouping3 ) );
converted << n;
return converted.str();
}
will need #include <locale> in some environments
A possible solution for the assignment could be:
std::string commas( std::string&& str )
{
return str.length() > 3?
commas( str.substr( 0, str.length()-3 ) ) + "," + str.substr( str.length()-3 ):
str;
}
std::string commas( int n )
{
std::ostringstream converted;
converted << n;
return commas( converted.str() );
}

Related

Reversing A String in C++ (Using Recursion)

#include <iostream>
#include <string>
using namespace std;
void ReverseString(string &S, int size)
{
static int start = 0;
if (start == size - 1 || start == size)
{
return;
}
else
{
swap(S[start++], S[size - 1]);
ReverseString(S, size - 1);
}
}
int main()
{
cout << "enter a string to reverse" << endl;
string s;
getline(cin, s);
cout << "Before Reversing" << endl;
cout << s << endl;
ReverseString(s, s.size());
cout << "After Reversing" << endl;
cout << s << endl;
return 0;
}
I am trying to nail recursions as much as i can,and i was trying to reverse a string using recursion
i didn't know how to do it at first,tried many different ways to do it,but i saw code samples on string reversing,but none of it made sense to me,so i made my own one,but not quite sure of it,i'm just asking for opinion,is it clean and functional??
Thank You
Using a function local static variable in a recursive function is a bad idea. Recursive functions should get all their state as input arguments.
Here's a simplified version that divides the logic into two functions.
void ReverseString(string &S, int start, int end)
{
if ( start < end )
{
swap(S[start], S[end - 1]);
ReverseString(S, start+1, end - 1);
}
}
void ReverseString(string &S)
{
ReverseString(S, 0, S.size());
}
Most of the time, higher level functions would only call the second function. The first function can be called from a higher level function if there is a need to reverse only a subset of a string.
Here's a sample program
#include <iostream>
#include <string>
using namespace std;
void ReverseString(string &S, int start, int end)
{
if ( start < end )
{
swap(S[start], S[end - 1]);
ReverseString(S, start+1, end - 1);
}
}
void ReverseString(string &S)
{
ReverseString(S, 0, S.size());
}
int main()
{
string s = "The string to reverse" ;
cout << "Before Reversing" << endl;
cout << s << endl;
ReverseString(s);
cout << "After Reversing" << endl;
cout << s << endl;
ReverseString(s, 0, 7);
cout << "After Reversing a subset" << endl;
cout << s << endl;
return 0;
}
and its output
Before Reversing
The string to reverse
After Reversing
esrever ot gnirts ehT
After Reversing a subset
reverse ot gnirts ehT
See it working at https://ideone.com/9nMlsP.
is it ... functional??
If by "functional" you mean "does it work", then you tell me.
If you mean "functional" as in "functional" programming style, then no it isn't. In functional style, you don't modify arguments in place, but instead return a new value. Also relying on global state (i.e. static objects) is very anti-functional.
Here is an example:
std::string
ReverseString(std::string_view sv)
{
if (sv.empty())
return "";
std::string_view x = sv.substr(0, 1)
std::string_view xs = sv.substr(1);
return ReverseString(xs) + x;
}
// usage
s = ReverseString(s);
In future, if Pattern matching was introduced to the language, then it could potentially be written like this:
std::string
ReverseString(std::string_view sv)
{
inspect(sv) {
"": return "";
[x:xs]: return ReverseString(xs) + x;
}
}
However, the current proposal does not suggest introducing support for matching ranges like this, so this is highly theoretical.
Local static variables are dangerous. Since their state will remain between function calls. In my approach i used slen as the length of a string and the currentIndex as the last swapped index on the string. Since it is enough to swap till the middle of the string, finish case is when (currentIndex == slen/2).
I also added some test cases as an example.(even length, odd length, zero case and palindrome)
#include <iostream>
#include <string>
using namespace std;
void ReverseString(string &S, int currentIndex, int slen)
{
if (slen / 2 == currentIndex) return;
swap(S[currentIndex], S[slen - 1 - currentIndex]);
currentIndex++;
ReverseString(S, currentIndex, slen);
}
void testReverseString() {
string s = "";
ReverseString(s, 0, s.length());
assert(s == "");
s = "ahmet";
ReverseString(s, 0, s.length());
assert(s == "temha");
s = "ahaha";
ReverseString(s, 0, s.length());
assert(s == "ahaha");
s = "haha";
ReverseString(s, 0, s.length());
assert(s == "ahah");
}
int main()
{
testReverseString();
return 0;
}
Your function with a static variable can be called only once because after its recursive calls the static variable start will not be equal to 0 as it is required. So the function is not "functional".
Here is a demonstrative program that shows how the function can be written with using a static variable and without using a static variable.
#include <iostream>
#include <string>
#include <utility>
void ReverseString1( std::string &s )
{
static std::string::size_type i = 0;
if ( not ( s.size() - 2 * i < 2 ) )
{
std::swap( s[i], s[s.size() - i - 1] );
++i;
ReverseString1( s );
--i;
}
}
void ReverseString2( std::string &s, std::string::size_type pos = 0 )
{
if ( not ( s.size() - 2 * pos < 2 ) )
{
std::swap( s[pos], s[s.size() - pos - 1] );
ReverseString2( s, pos + 1 );
}
}
int main()
{
std::string s( "Hello World!" );
std::cout << s << '\n';
ReverseString1( s );
std::cout << s << '\n';
ReverseString2( s );
std::cout << s << '\n';
return 0;
}
The program output is
Hello World!
!dlroW olleH
Hello World!
Anyone can reverse a string one char at a time, but much cooler is to reverse each third of the string and swap the outer thirds. This cuts stack depth as well as sowing confusion amongst the competition. Note that max stack depth of recursion per character is N, whereas this is cube root of N.
#include <iostream>
#include <string>
using namespace std;
void ReverseRegion(string &s, int start, int sz)
{
// regions < 2 need no action
if (sz == 2) {
char tmp = s[start];
s[start] = s[start+1];
s[start+1] = tmp;
} else if (sz > 2) {
int s3 = sz/3;
ReverseRegion(s, start, s3);
string tmp = s.substr(0,start) + s.substr(start+sz-s3,s3) + s.substr(start+s3, sz-2*s3) + s.substr(start,s3) + s.substr(start+sz);
// cout << "do: " << tmp << "\n";
s = tmp;
ReverseRegion(s, start+s3, sz-2*s3);
ReverseRegion(s, start, s3);
}
}
void ReverseString(string &S)
{
ReverseRegion(S, 0, S.size());
}
int main()
{
cout << "enter a string to reverse" << endl;
string s;
getline(cin, s);
cout << "Before Reversing" << endl;
cout << s << endl;
ReverseString(s);
cout << "After Reversing" << endl;
cout << s << endl;
return 0;
}

Getting the text of the last directory of a given string with the delimiters of /

Given a URL (which is a string) such as this:
www.testsite.com/pictures/banners/whatever/
I want to be able to get the characters of the last directory in the URL (in this case it's "whatever", I want to also remove the forward slashes). What would be the most efficient way to do this?
Thanks for any help
#include <iostream>
#include <string>
std::string getlastcomponent(std::string s) {
if (s.size() > 0 && s[s.size()-1] == '/')
s.resize(s.size() - 1);
size_t i = s.find_last_of('/');
return (i != s.npos) ? s.substr(i+1) : s;
}
int main() {
std::string s1 = "www.testsite.com/pictures/banners/whatever/";
std::string s2 = "www.testsite.com/pictures/banners/whatever";
std::string s3 = "whatever/";
std::string s4 = "whatever";
std::cout << getlastcomponent(s1) << '\n';
std::cout << getlastcomponent(s2) << '\n';
std::cout << getlastcomponent(s3) << '\n';
std::cout << getlastcomponent(s4) << '\n';
return 0;
}
Get the length and push every letter from last ( at example pseudo code:
x = string.length()
while(X != 0)
{
CharVector.push(string.at(x));
x--;
if(string.at(x) == "\") break;
}
then you got revetahw instead of whatever.
Then just swap it with this fucntion:
string ReverseString( const string& word )
{
std::string l_bla;
bla.reserve(word.size());
for ( string::size_type x = word.length ( ); x > 0; x-- )
{
l_bla += word.at ( x -1 );
}
return l_bla;
}
so you got whatever

Extract integer from a string

I have string like "y.x-name', where y and x are number ranging from 0 to 100. From this string, what would be the best method to extract 'x' into an integer variable in C++.
You could split the string by . and convert it to integer type directly. The second number in while loop is the one you want, see sample code:
template<typename T>
T stringToDecimal(const string& s)
{
T t = T();
std::stringstream ss(s);
ss >> t;
return t;
}
int func()
{
string s("100.3-name");
std::vector<int> v;
std::stringstream ss(s);
string line;
while(std::getline(ss, line, '.'))
{
v.push_back(stringToDecimal<int>(line));
}
std::cout << v.back() << std::endl;
}
It will output: 3
It seem that this thread has a problem similar to you, it might help ;)
Simple string parsing with C++
You can achieve it with boost::lexical_cast, which utilizes streams like in billz' answer:
Pseudo code would look like this (indices might be wrong in that example):
std::string yxString = "56.74-name";
size_t xStart = yxString.find(".") + 1;
size_t xLength = yxString.find("-") - xStart;
int x = boost::lexical_cast<int>( yxString + xStart, xLength );
Parsing errors can be handled via exceptions that are thrown by lexical_cast.
For more flexible / powerful text matching I suggest boost::regex.
Use two calls to unsigned long strtoul( const char *str, char **str_end, int base ), e.g:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(){
char const * s = "1.99-name";
char *endp;
unsigned long l1 = strtoul(s,&endp,10);
if (endp == s || *endp != '.') {
cerr << "Bad parse" << endl;
return EXIT_FAILURE;
}
s = endp + 1;
unsigned long l2 = strtoul(s,&endp,10);
if (endp == s || *endp != '-') {
cerr << "Bad parse" << endl;
return EXIT_FAILURE;
}
cout << "num 1 = " << l1 << "; num 2 = " << l2 << endl;
return EXIT_FAILURE;
}

Return fixed length std::string from integer value

Problem -> To return fixed length string to std::string*.
Target machine -> Fedora 11 .
I have to derive a function which accepts integer value and return fixed lenght string to a string pointer;
for example -> int value are in range of 0 to -127
so for int value 0 -> it shoud display 000
for value -9 -> it should return -009
for value say -50 -> it should return -050
for value say -110 -> it should return -110
so in short , lenght should be same in all cases.
What I have done : I have defined the function according to the requirement which has shown below.
Where I need help: I have derived a function but I am not sure if this is correct approach. When I test it on standalone system on windows side , the exe stopped working after sometimes but when I include this function with the overall project on Linux machine , it works flawlessly.
/* function(s)to implement fixed Length Rssi */
std::string convertString( const int numberRssi, std::string addedPrecison="" )
{
const std::string delimiter = "-";
stringstream ss;
ss << numberRssi ;
std::string tempString = ss.str();
std::string::size_type found = tempString.find( delimiter );
if( found == std::string::npos )// not found
{
tempString = "000";
}
else
{
tempString = tempString.substr( found+1 );
tempString = "-" +addedPrecison+tempString ;
}
return tempString;
}
std::string stringFixedLenght( const int number )
{
std::string str;
if( (number <= 0) && (number >= -9) )
{
str = convertString( number, "00");
}
else if( (number <= -10) && (number >= -99) )
{
str = convertString( number, "0");
}
else
{
str= convertString(number, "");
}
return str;
}
// somewhere in the project calling the function
ErrorCode A::GetNowString( std::string macAddress, std::string *pString )
{
ErrorCode result = ok;
int lvalue;
//some more code like iopening file and reading file
//..bla
// ..bla
// already got the value in lvalue ;
if( result == ok )
{
*pString = stringFixedLenght( lValue );
}
// some more code
return result;
}
You can use I/O manipulators to set the width that you need, and fill with zeros. For example, this program prints 00123:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << setfill('0') << setw(5) << 123 << endl;
return 0;
}
You have to take care of the negative values yourself, though: cout << setfill('0') << setw(5) << -123 << endl prints 0-123, not -0123. Check if the value is negative, set the width to N-1, and add a minus in front.
How about using std::ostringstream and the standard output formatting manipulators?
std::string makeFixedLength(const int i, const int length)
{
std::ostringstream ostr;
if (i < 0)
ostr << '-';
ostr << std::setfill('0') << std::setw(length) << (i < 0 ? -i : i);
return ostr.str();
}
Note that your examples contradict your description: if the value is -9,
and the fixed length is 3, should the output be "-009" (as in your
example), or "-09" (as you describe)? If the former, the obvious
solution is to just use the formatting flags on std::ostringstream:
std::string
fixedWidth( int value, int width )
{
std::ostringstream results;
results.fill( '0' );
results.setf( std::ios_base::internal, std::ios_base::adjustfield );
results << std::setw( value < 0 ? width + 1 : width ) << value;
return results.str();
}
For the latter, just drop the conditional in the std::setw, and pass
width.
For the record, although I would avoid it, this is one of the rare cases
where printf does something better than ostream. Using snprintf:
std::string
fixedWidth( int value, int width )
{
char buffer[100];
snprintf( buffer, sizeof(buffer), "%.*d", width, value );
return buffer;
}
You'd probably want to capture the return value of snprintf and add
some error handling after it, just in case (but 100 chars is
sufficient for most current machines).
I have nothing against the versions that use streams, but you can do it all yourself more simply than your code:
std::string fixedLength(int value, int digits = 3) {
unsigned int uvalue = value;
if (value < 0) {
uvalue = -uvalue;
}
std::string result;
while (digits-- > 0) {
result += ('0' + uvalue % 10);
uvalue /= 10;
}
if (value < 0) {
result += '-';
}
std::reverse(result.begin(), result.end());
return result;
}
like this?
#include <cstdlib>
#include <string>
template <typename T>
std::string meh (T x)
{
const char* sign = x < 0 ? "-" : "";
const auto mag = std::abs (x);
if (mag < 10) return sign + std::string ("00" + std::to_string(mag));
if (mag < 100) return sign + std::string ("0" + std::to_string(mag));
return std::to_string(x);
}
#include <iostream>
int main () {
std::cout << meh(4) << ' '
<< meh(40) << ' '
<< meh(400) << ' '
<< meh(4000) << '\n';
std::cout << meh(-4) << ' '
<< meh(-40) << ' '
<< meh(-400) << ' '
<< meh(-4000) << '\n';
}
004 040 400 4000
-004 -040 -400 -4000

Formatting an integer in C++

I have an 8 digit integer which I would like to print formatted like this:
XXX-XX-XXX
I would like to use a function that takes an int and returns a string.
What's a good way to do this?
This is how I'd do it, personally. Might not be the fastest way of solving the problem, and definitely not as reusable as egrunin's function, but it strikes me as both clean and easy to understand. I'll throw it in the ring as an alternative to the mathier and loopier solutions.
#include <sstream>
#include <string>
#include <iomanip>
std::string format(long num) {
std::ostringstream oss;
oss << std::setfill('0') << std::setw(8) << num;
return oss.str().insert(3, "-").insert(6, "-");
};
Tested this, it works.
The format parameter here is "XXX-XX-XXX", but it only looks at (and skips over) the dashes.
std::string foo(char *format, long num)
{
std::string s(format);
if (num < 0) { return "Input must be positive"; }
for (int nPos = s.length() - 1; nPos >= 0; --nPos)
{
if (s.at(nPos) == '-') continue;
s.at(nPos) = '0' + (num % 10);
num = num / 10;
}
if (num > 0) { return "Input too large for format string"; }
return s;
}
Usage:
int main()
{
printf(foo("###-##-###", 12345678).c_str());
return 0;
}
Here's a bit different way that tries to work with the standard library and get it to do most of the real work:
#include <locale>
template <class T>
struct formatter : std::numpunct<T> {
protected:
T do_thousands_sep() const { return T('-'); }
std::basic_string<T> do_grouping() const {
return std::basic_string<T>("\3\2\3");
}
};
#ifdef TEST
#include <iostream>
int main() {
std::locale fmt(std::locale::classic(), new formatter<char>);
std::cout.imbue(fmt);
std::cout << 12345678 << std::endl;
return 0;
}
#endif
To return a string, just write to a stringstream, and return its .str().
This may be overkill if you only want to print out one number that way, but if you want to do this sort of thing in more than one place (or, especially, if you want to format all numbers going to a particular stream that way) it becomes more reasonable.
Here's a complete program that shows how I'd do it:
#include <iostream>
#include <iomanip>
#include <sstream>
std::string formatInt (unsigned int i) {
std::stringstream s;
s << std::setfill('0') << std::setw(3) << ((i % 100000000) / 100000) << '-'
<< std::setfill('0') << std::setw(2) << ((i % 100000) / 1000) << '-'
<< std::setfill('0') << std::setw(3) << (i % 1000);
return s.str();
}
int main (int argc, char *argv[]) {
if (argc > 1)
std::cout << formatInt (atoi (argv[1])) << std::endl;
else
std::cout << "Provide an argument, ya goose!" << std::endl;
return 0;
}
Running this with certain inputs gives:
Input Output
-------- ----------
12345678 123-45-678
0 000-00-000
7012 000-07-012
10101010 101-01-010
123456789 234-56-789
-7 949-67-289
Those last two show the importance of testing. If you want different behaviour, you'll need to modify the code. I generally opt for silent enforcement of rules if the caller can't be bothered (or is too stupid) to follow them but apparently some people like to use the principle of least astonishment and raise an exception :-)
You can use the std::ostringstream class to convert the number to a string. Then you can use the string of digits and print them using whatever formatting you want, as in the following code:
std::ostringstream oss;
oss << std::setfill('0') << std::setw(8) << number;
std::string str = oss.str();
if ( str.length() != 8 ){
// some form of handling
}else{
// print digits formatted as desired
}
int your_number = 12345678;
std::cout << (your_number/10000000) % 10 << (your_number/1000000) % 10 << (your_number/100000) %10 << "-" << (your_number/10000) %10 << (your_number/1000) %10 << "-" << (your_number/100) %10 << (your_number/10) %10 << (your_number) %10;
http://www.ideone.com/17eRv
Its not a function, but its a general method for parsing an int number by number.
#include <iostream>
#include <string>
using namespace std;
template<class Int, class Bi>
void format(Int n, Bi first, Bi last)
{
if( first == last ) return;
while( n != 0 ) {
Int t(n % 10);
n /= 10;
while( *--last != 'X' && last != first);
*last = t + '0';
}
}
int main(int argc, char* argv[])
{
int i = 23462345;
string s("XXX-XX-XXX");
format(i, s.begin(), s.end());
cout << s << endl;
return 0;
}
How's this?
std::string format(int x)
{
std::stringstream ss
ss.fill('0');
ss.width(3);
ss << (x / 10000);
ss.width(1);
ss << "-";
ss.width(2);
ss << (x / 1000) % 100;
ss.width(1);
ss << "-";
ss.width(3);
ss << x % 1000;
return ss.str();
}
Edit 1: I see strstream is deprecated and replaced with stringstream.
Edit 2: Fixed issue of missing leading 0's. I know, it's ugly.
Obviously a char * and not a string, but you get the idea. You'll need to free the output once you're done, and you should probably add error checking, but this should do it:
char * formatter(int i)
{
char *buf = malloc(11*sizeof(char));
sprintf(buf, "%03d-%02d-%03d", i/100000, (i/1000)%100, i%1000);
return buf;
}
You don't require malloc or new, just define buf as char buff[11];