Increment numerical string

From Rosetta Code

Jump to: navigation, search

Programming Task
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.

Code examples should be formatted along the lines of one of the existing prototypes.

This task is about incrementing a numerical string.

Contents

[edit] Ada

The standard Ada package Ada.Strings.Fixed provides a function for trimming blanks from a string.

 
 S : String := "12345";
 S := Ada.Strings.Fixed.Trim(Source => Integer'Image(Integer'Value(S) + 1), Side => Ada.Strings.Both);
 

[edit] BASIC

Works with: QuickBasic version 4.5

Works with: PB version 7.1

 s$ = "12345"
 s$ = STR$(VAL(s$) + 1)

[edit] C

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 char s[] = "12345";
 // Using atoi
 int i = atoi(s) + 1;

 // Using strtol
 int i = (int)strtol(s, NULL, 10) + 1;
 // Using sprintf
 sprintf(s, "%d", i);

 // Using itoa (not standard)
 itoa(i, s, 10);

[edit] C++

Library: STL

 // STL with string stream operators
 #include <cstdlib>
 #include <string>
 #include <sstream>
 using namespace std;
 std::string s = "12345";
 int i = atoi((const char*)s.c_str()) + 1;
 std::ostringstream oss;
 if (oss << i) s = oss.str();

Library: Boost

 // Boost
 #include <cstdlib>
 #include <string>
 #include <boost/lexical_cast.hpp>
 
 std::string s = "12345";
 int i = boost::lexical_cast<int>(s) + 1;
 s = boost::lexical_cast<std::string>(i);

Library: Qt

 // Qt
 QString s = "12345";
 int i = atoi((const char*)s.data()) + 1;
 // Using constructor(int, base)
 QString s2(i, 10);
 s = s2;
 // Using setNum(int)
 s.setNum(i);


Library: MFC

 // MFC
 CString s = "12345";
 int i = _ttoi(s) + 1;
 int i = _tcstoul(s, NULL, 10) + 1; 
 s.Format("%d", i);

All of the above solutions only work for numbers <= INT_MAX. The following works for an (almost) arbitrary large number:

Works with: g++ version 4.0.2

 #include <string>
 #include <iostream>
 #include <ostream>
 
 void increment_numerical_string(std::string& s)
 {
   std::string::reverse_iterator iter = s.rbegin(), end = s.rend();
   int carry = 1;
   while (carry && iter != end)
   {
     int value = (*iter - '0') + carry;
     carry = (value / 10);
     *iter = '0' + (value % 10);
     ++iter;
   }
   if (carry)
     s.insert(0, "1");
 }
 
 int main()
 {
   std::string big_number = "123456789012345678901234567899";
   std::cout << "before increment: " << big_number << "\n";
   increment_numerical_string(big_number);
   std::cout << "after increment:  " << big_number << "\n";
 }

[edit] C#

 string s = "12345";
 int i = int.Parse(s) + 1;
 s = i.ToString();

[edit] Common Lisp

(princ-to-string (1+ (parse-integer "1234")))

[edit] D

import std.conv, std.string;
...
auto n = toString(toInt("12345") + 1);

[edit] E

__makeInt("1234", 10).next().toString(10)

[edit] Forth

This word causes the number whose string value is stored at the given location to be incremented. The address passed must contain enough space to hold the string representation of the new number. Error handling is rudimentary, and consists of aborting when the string does not contain a numerical value.

The word ">string" takes and integer and returns the string representation of that integer. I factored it out of the definitions below to keep the example simpler.

: >string ( d -- addr n )
  dup >r dabs <# #s r> sign #> ;

: inc-string ( addr -- )
  dup count number? not abort" invalid number"
  1 s>d d+ >string rot place ;

Here is a version that can increment by any value

: inc-string ( addr n -- )
  over count number? not abort" invalid number"
  rot s>d d+  >string rot place ;

Test the first version like this:

s" 123" pad place
pad inc-string
pad count type

And the second one like this:

s" 123" pad place
pad 1 inc-string
pad count type

[edit] Haskell

(show . (+1) . read) "1234"

[edit] IDL

str = '1234'
print, string(fix(str)+1)
;==>   1235

[edit] J

incrTextNum=: >:&.".

or

incrTextNum=: >:&.:".

or

incrTextNum=: >:&.(_&".)

The formulation you choose depends upon the details of your desired input and ouput. Examples follow. (Note that in addition to working for a single numeric value, this will increment multiple values provided within the same string, on a variety of number types and formats.)

   incrTextNum '34.5'
35.5
   incrTextNum '7 0.2 3r5 2j4 5.7e-4'
8      
1.2    
1.6    
3j4    
1.00057

[edit] Java

 String s = "12345";
 s = (Integer.parseInt(s) + 1) + "";

[edit] JavaScript

 var s = "12345";
 var i = parseInt(s) + 1;
 s = i;

A faster way instead of parseInt:

 var i = (+s)+1;

[edit] LaTeX

\documentclass{article}

% numbers are stored in counters
\newcounter{tmpnum}

% macro to increment a string (given as argument)
\newcommand{\stringinc}[1]{%
\setcounter{tmpnum}{#1}%     setcounter effectively converts the string to a number
\stepcounter{tmpnum}%        increment the counter; alternatively: \addtocounter{tmpnum}{1}
\arabic{tmpnum}%             convert counter value to arabic (i.e. decimal) number string
}

%example usage
\begin{document}
The number 12345 is followed by \stringinc{12345}.
\end{document}

[edit] MAXScript

str = "12345"
str = ((str as integer) + 1) as string

[edit] OCaml

string_of_int (succ (int_of_string "1234"))

[edit] Perl

 my $s = "12345";
 $s++;

[edit] PHP

 $s = "12345";
 $s++;

[edit] Pop11

lvars s = '123456789012123456789999999999';
(strnumber(s) + 1) >< '' -> s;

[edit] Python

Works with: Python version 2.3, 2.4, and 2.5

next = str(int('123') + 1)

[edit] R

s = "12345"
as.numeric(s) + 1

[edit] Ruby

If a string represents a number, the succ method will increment the number:

'1234'.succ #=> '1235'
'99'.succ #=> '100'

[edit] Scheme

(number->string (+ 1 (string->number "1234")))

[edit] Seed7

 var string: s is "12345";
 s := str(succ(integer parse s));

[edit] Tcl

In the end, all variables are strings in Tcl. A "number" is merely a particular interpretation of a string of bytes.

set str 1234
incr str

[edit] Toka

" 100" >number drop 1 + >string
Personal tools