Zurück zu Pi7.eu
BLOG
Add Comma to Number-String (C++)
C++
// addCommaToNumberString: // The In-/Output Buffer char* numberString has to be large enough to contain additional commas // int length is the length of the input string (or amount of digits) void addCommaToNumberString( char* numberString, int &length ) { int readPos = length - 1; // pos is the index of the last digit in the remaining string to work on length += readPos / 3; // !Integer Division! ~ Add the amount of commas that will be added to the length int writePos= length - 1; while( readPos > 2 ) // For each tripple of digits: { numberString[ writePos - 0 ] = numberString[ readPos - 0 ]; numberString[ writePos - 1 ] = numberString[ readPos - 1 ]; numberString[ writePos - 2 ] = numberString[ readPos - 2 ]; numberString[ writePos - 3 ] = ','; readPos -= 3; writePos -= 4; } }


Example:
Step String Action
input 123456789012########## -> todo: add 3 commas (3 additional signs to write) (# represent unwritten space)
comma 123456789012##2####### -> copy first 3 digit to the end (3 signs further, as we have 3 commas left to add)
123456789012#12#######
123456789012012#######
12345678901,012####### -> add comma -> 2 commas left now
12345678909,012#######
12345678989,012#######
12345678789,012#######
1234567,789,012####### -> add comma -> 1 comma left
1234566,789,012#######
1234556,789,012#######
1234456,789,012#######
123,456,789,012####### -> add last comma
= > done! "123,456,789,012" is our new String.
Autor: Pierre
erstellt am 02.08.2013 10:20 - aktualisiert am 02.08.2013 11:31
952 Aufrufe
...
You can share this Blog on Facebook, Google+ and Twitter! ... what about Skype?
Pascal

05.08.2013 10:19





HHÄÄÄ[?