Increment a numerical string

From Rosetta Code
Revision as of 07:11, 14 January 2011 by rosettacode>Presidentbeef (Add Brat solution)
Increment a numerical string
You are encouraged to solve this task according to the task description, using any language you may know.

This task is about incrementing a numerical string.


<lang ABAP>report zz_incstring perform test using: '0', '1', '-1', '10000000', '-10000000'.

form test using iv_string type string.

 data: lv_int  type i,
       lv_string type string.
 lv_int = iv_string + 1.
 lv_string = lv_int.
 concatenate '"' iv_string '" + 1 = "' lv_string '"' into lv_string.
 write / lv_string.

endform. </lang>


"0" + 1 = "1 "
"1" + 1 = "2 "
"-1" + 1 = "0 "
"10000000" + 1 = "10000001 "
"-10000000" + 1 = "9999999-"


<lang ActionScript>function incrementString(str:String):String { return String(Number(str)+1); }</lang>


The standard Ada package Ada.Strings.Fixed provides a function for trimming blanks from a string. <lang ada>S : String := "12345"; S := Ada.Strings.Fixed.Trim(Source => Integer'Image(Integer'Value(S) + 1), Side => Ada.Strings.Both);</lang>


Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

<lang algol68>STRING s := "12345"; FILE f; INT i; associate(f, s); get(f,i); i+:=1; s:=""; reset(f); put(f,i); print((s, new line))</lang> Output:



<lang autohotkey>str = 12345 MsgBox % str += 1</lang> Output:



<lang autoIt>Global $x = "12345" $x += 1 MsgBox(0,"",$x)</lang> Output:



The example shows that the string s can be incremented, but after that still is a string of length 2. <lang awk>$ awk 'BEGIN{s="42";s++;print s"("length(s)")"}' 43(2)</lang>


Works with: QBasic
Works with: PowerBASIC
Works with: Visual Basic
Works with: Liberty BASIC

<lang qbasic>s$ = "12345" s$ = STR$(VAL(s$) + 1)</lang>

ZX Spectrum Basic

The ZX Spectrum needs line numbers and a let statement, but the same technique can be used:

<lang basic> 10 LET s$ = "12345" 20 LET s$ = STR$(VAL(s$) + 1) </lang>

Batch File

Since environment variables have no type distinction all numbers are simply numeric strings:

Works with: Windows NT version 4

<lang dos>set s=12345 set /a s+=1</lang>


<lang brat>#Convert to integer, increment, then back to string p ("100".to_i + 1).to_s #Prints 101</lang>


<lang c>#include <stdio.h>

  1. include <stdlib.h>
  2. include <string.h>

void test(const char *s) {

  char rbuf[32];
  int i;
  /* Multiple standard functions can convert strings to integers:
     sscanf(s, "%d", &i);
     i = (int)strtol(s, NULL, 10);
     i = atoi(s);
  i = atoi(s);
  /* The standard sprintf functions can convert integers to strings.
     A function called itoa is also common, however it is not standard.
     itoa(i+1, rbuf, 10);
  snprintf(rbuf, 32, "%d", i+1);
  printf("\"%s\" + 1 = \"%s\"\n", s, rbuf);


int main(void) {

  return 0;



"0" + 1 = "1"
"1" + 1 = "2"
"-1" + 1 = "0"
"1000000000" + 1 = "1000000001"
"-1000000000" + 1 = "-999999999"


Library: STL

<lang cpp>// STL with string stream operators

  1. include <cstdlib>
  2. include <string>
  3. include <sstream>

// inside a function or method... std::string s = "12345";

int i; std::istringstream(s) >> i; i++; //or: //int i = std::atoi(s.c_str()) + 1;

std::ostringstream oss; if (oss << i) s = oss.str();</lang>

Library: Boost

<lang cpp>// Boost

  1. include <cstdlib>
  2. include <string>
  3. include <boost/lexical_cast.hpp>

// inside a function or method... std::string s = "12345"; int i = boost::lexical_cast<int>(s) + 1; s = boost::lexical_cast<std::string>(i);</lang>

Library: Qt
Uses: Qt (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses Library" (as page type) with input value "Library/Qt/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})

<lang cpp>// Qt QString num1 = "12345"; QString num2 = QString("%1").arg(v1.toInt()+1);</lang>

Library: MFC
Uses: Microsoft Foundation Classes (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses Library" (as page type) with input value "Library/Microsoft Foundation Classes/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})
Uses: C Runtime (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses Library" (as page type) with input value "Library/C Runtime/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})

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

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

<lang cpp>#include <string>

  1. include <iostream>
  2. 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);
   if (carry)
       s.insert(0, "1");


int main() {

   std::string big_number = "123456789012345678901234567899";
   std::cout << "before increment: " << big_number << "\n";
   std::cout << "after increment:  " << big_number << "\n";



<lang csharp>string s = "12345"; s = (int.Parse(s) + 1).ToString();</lang>


<lang lisp>(str (inc (Integer/parseInt "1234")))</lang>

Common Lisp

<lang lisp>(princ-to-string (1+ (parse-integer "1234")))</lang>


<lang d>import std.conv, std.string; ... auto n = toString(toInt("12345") + 1);</lang>

the same can be done in
Library: tango
using the import:

<lang D>import tango.text.convert.Integer;</lang>


<lang e>__makeInt("1234", 10).next().toString(10)</lang>


<lang erlang>integer_to_list(list_to_integer("1336")+1).</lang>


<lang factor>"1234" string>number 1 + number>string</lang>


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.

<lang forth>: >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 ;</lang>

Here is a version that can increment by any value

<lang forth>: inc-string ( addr n -- )

 over count number? not abort" invalid number"
 rot s>d d+  >string rot place ;</lang>

Test the first version like this:

<lang forth>s" 123" pad place pad inc-string pad count type</lang>

And the second one like this:

<lang forth>s" 123" pad place pad 1 inc-string pad count type</lang>


Works with: Fortran version 90 and later

Using 'internal' files you can increment both integer and real strings <lang fortran>CHARACTER(10) :: intstr = "12345", realstr = "1234.5" INTEGER :: i REAL :: r

READ(intstr, "(I10)") i  ! Read numeric string into integer i i = i + 1  ! increment i WRITE(intstr, "(I10)") i  ! Write i back to string

READ(realstr, "(F10.1)") r r = r + 1.0 WRITE(realstr, "(F10.1)") r</lang>


<lang gap># Using built-in functions Incr := s -> String(Int(s) + 1);

  1. Implementing addition
  2. (but here 9...9 + 1 = 0...0 since the string length is fixed)

Increment := function(s)

 local c, n, carry, digits;
 digits := "0123456789";
 n := Length(s);
 carry := true;
 while n > 0 and carry do
   c := Position(digits, s[n]) - 1; 
   if carry then
     c := c + 1;
   if c > 9 then
     carry := true;
     c := c - 10;
     carry := false;
   s[n] := digits[c + 1];
   n := n - 1;


s := "2399"; Increment(s); s;

  1. "2400"</lang>


<lang go>package main import "fmt" import "strconv" func main() {

 i, _ := strconv.Atoi("1234")
 fmt.Println(strconv.Itoa(i + 1))



Solution: <lang groovy>println ((("23455" as BigDecimal) + 1) as String) println ((("23455.78" as BigDecimal) + 1) as String)</lang>




<lang haskell>(show . (+1) . read) "1234"</lang>


<lang hicest>CHARACTER string = "123 -4567.89"

  READ( Text=string) a,   b
  WRITE(Text=string) a+1, b+1 ! 124 -4566.89</lang>

Icon and Unicon

Icon and Unicon will automatically coerce type conversions where they make sense. Where a conversion can't be made to a required type a run time error is produced.

<lang Icon>s := "123" # s is a string s +:= 1# s is now an integer</lang>


<lang idl>str = '1234' print, string(fix(str)+1)

==> 1235</lang>

In fact, IDL tries to convert types cleverly. That works, too:

<lang idl>print, '1234' + 1

==> 1235</lang>

Inform 7

This solution works for numbers that fit into a single word (16-bit signed int for Z-machine, 32-bit signed int for Glulx virtual machine). <lang inform7>Home is a room.

To decide which indexed text is incremented (T - indexed text): let temp be indexed text; let temp be the player's command; change the text of the player's command to T; let N be a number; if the player's command matches "[number]": let N be the number understood; change the text of the player's command to temp; decide on "[N + 1]".

When play begins: say incremented "12345"; end the story.</lang>


<lang j>incrTextNum=: >:&.".</lang>

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 including rational and complex numbers. <lang j> incrTextNum '34.5' 35.5

  incrTextNum '7 0.2 3r5 2j4 5.7e_4'

8 1.2 1.6 3j4 1.00057</lang>

Note also that the result here is a list of characters, and not a list of integers, which becomes obvious when you manipulate the result. For example, consider the effect of reversing the contents of the list:

<lang j> |.incrTextNum'123 456' 754 421

  |.1+123 456

457 124</lang>


When using Integer.parseInt in other places, it may be beneficial to call trim on the String, since parseInt will throw an Exception if there are spaces in the String. <lang java>String s = "12345"; s = String.valueOf(Integer.parseInt(s) + 1);</lang>


<lang javascript>var s = "12345"; s = (Number(s) + 1).toString();</lang> </lang>


<lang 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}</lang>

Liberty BASIC

<lang lb>' [RC] Increment a numerical string.

o$ ="12345" print o$

v =val( o$) o$ =str$( v +1) print o$


Logo is weakly typed, so numeric strings can be treated as numbers and numbers can be treated as strings. <lang logo>show "123 + 1  ; 124 show word? ("123 + 1) ; true</lang>


<lang logtalk>number_chars(Number, "123"), Number2 is Number+1, number_chars(Number2, String2)</lang>


<lang lua>print(tonumber("2345")+1)</lang>


M4 can handle only integer signed 32 bit numbers, and they can be only written as strings <lang m4>define(`V',`123')dnl define(`VN',`-123')dnl eval(V+1) eval(VN+1)</lang>

If the expansion of any macro in the argument of eval gives something that can't be interpreted as an expression, an error is raised (but the interpretation of the whole file is not stopped)


<lang Mathematica>Print[FromDigits["1234"] + 1]</lang>


<lang MATLAB>function numStr = incrementNumStr(numStr)

   numStr = num2str(str2double(numStr) + 1);



<lang maxscript>str = "12345" str = ((str as integer) + 1) as string</lang>


<lang metafont>string s; s := "1234"; s := decimal(scantokens(s)+1); message s;</lang>


Modula-3 provides the module Scan for lexing. <lang modula3>MODULE StringInt EXPORTS Main;

IMPORT IO, Fmt, Scan;

VAR string: TEXT := "1234";

   num: INTEGER := 0;


 num := Scan.Int(string);
 IO.Put(string & " + 1 = " & Fmt.Int(num + 1) & "\n");

END StringInt.</lang> Output:

1234 + 1 = 1235


Just add. <lang MUMPS>

SET STR="123"



<lang objc>NSString *s = @"12345"; int i = [s intValue] + 1; s = [NSString stringWithFormat:@"%i", i]</lang>


<lang objeck> s := "12345"; i := int->ToInt(s) + 1; s := i->ToString(); </lang>


<lang ocaml>string_of_int (succ (int_of_string "1234"))</lang>


We convert the string to a number, increment it, and convert it back to a string.

<lang octave>nstring = "123"; nstring = sprintf("%d", str2num(nstring) + 1); disp(nstring);</lang>


<lang oz>{Int.toString {String.toInt "12345"} + 1}</lang>




<lang perl>my $s = "12345"; $s++;</lang>

Perl 6

Works with: Rakudo version #22 "Thousand Oaks"

<lang perl6>my $s = "12345"; $s++;</lang>


<lang php>$s = "12345"; $s++;</lang>


<lang PicoLisp>(format (inc (format "123456")))</lang>


<lang PL/I> declare s picture '999999999'; s = '123456789'; s = s + 1; put skip list (s); </lang>

Plain TeX

<lang tex>\newcount\acounter \def\stringinc#1{\acounter=#1\relax% \advance\acounter by 1\relax% \number\acounter} The number 12345 is followed by \stringinc{12345}. \bye</lang>

The generated page will contain the text:

The number 12345 is followed by 12346.


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


The easiest way is to cast the string to int, incrementing it and casting back to string: <lang powershell>$s = "12345" $t = [string] ([int] $s + 1)</lang> One can also take advantage of the fact that PowerShell casts automatically according to the left-most operand to save one cast: <lang powershell>$t = [string] (1 + $s)</lang>


Works with SWI-Prolog. <lang Prolog>incr_numerical_string(S1, S2) :- string_to_atom(S1, A1), atom_number(A1, N1), N2 is N1+1, atom_number(A2, N2), string_to_atom(S2, A2). </lang> Output : <lang Prolog> ?- incr_numerical_string("123", S2). S2 = "124". </lang>


<lang PureBasic>string$="12345" string$=Str(Val(string$)+1) Debug string$</lang>


Works with: Python version 2.3, 2.4, 2.5, and 2.6

<lang python>next = str(int('123') + 1)</lang>


<lang r>s = "12345" s <- as.character(as.numeric(s) + 1)</lang>


<lang REBOL>REBOL [ Title: "Increment Numerical String" Author: oofoe Date: 2009-12-23 URL: ]

Note the use of unusual characters in function name. Also note that
because REBOL collects terms from right to left, I convert the
string argument (s) to integer first, then add that result to one.

s++: func [s][to-string 1 + to-integer s]

Examples. Because the 'print' word actually evaluates the block
(it's effectively a 'reduce' that gets printed space separated),
it's possible for me to assign the test string to 'x' and have it
printed as a side effect. At the end, 'x' is available to submit to
the 's++' function. I 'mold' the return value of s++ to make it
obvious that it's still a string.

print [x: "-99" "plus one equals" mold s++ x] print [x: "42" "plus one equals" mold s++ x] print [x: "12345" "plus one equals" mold s++ x]</lang>


-99 plus one equals "-98"
42 plus one equals "43"
12345 plus one equals "12346"


<lang Retro>"123" toNumber 1+ toString</lang>


Rexx, like many other scripting languages, uses typeless variables. Typeless variables are stored as variable length character strings and can be treated as either a string or a numeric value, depending on the context in which they are used.

<lang rexx> count = "3" /* Typeless variables are all strings */ count = count + 1 /* Variables in a numerical context are treated as numbers */ say count </lang>


If a string represents a number, the succ method will increment the number: <lang ruby>'1234'.succ #=> '1235' '99'.succ #=> '100'</lang>


The string needs to be converted to a numeric type. BigDecimal should handle most numeric strings. We define a method to do it.

<lang scala>implicit def toSucc(s: String) = new { def succ = BigDecimal(s) + 1 toString }</lang>


scala> "123".succ
res5: String = 124


<lang scheme>(number->string (+ 1 (string->number "1234")))</lang>


<lang seed7>var string: s is "12345";

s := str(succ(integer parse s));</lang>


<lang slate>((Integer readFrom: '123') + 1) printString</lang>


<lang smalltalk>('123' asInteger + 1) printString</lang>


<lang snobol4>

    output = trim(input) + 1
    output = "123" + 1






Standard ML

<lang sml>Int.toString (1 + valOf (Int.fromString "1234"))</lang>


In the end, all variables are strings in Tcl. A "number" is merely a particular interpretation of a string of bytes. <lang tcl>set str 1234 incr str</lang>


<lang ti89b>string(expr(str)+1)</lang>


<lang toka>" 100" >number drop 1 + >string</lang>

UNIX Shell

Works with: Bourne Shell
Works with: bash

Traditional Unix shell does not directly support arithmetic operations, so external tools, such as expr are used to perform arithmetic calculations when required. The following example demonstrates how a variable can be incremented by using the expr function:

<lang sh>

  1. All variables are strings within the shell
  2. Although num look like a number, it is in fact a numerical string

num=5 num=`expr $num + 1` # Increment the number </lang>

The korn shell and some newer shells do support arithmetic operations directly, and a several syntax options are available:

<lang ksh>

  1. All variables are strings within the shell
  2. Although num look like a number, it is in fact a numerical string

num=5 let num=num+1 # Increment the number let "num = num + 1" # Increment again. (We can use spaces inside quotes) num=$num+1 # Increment again. This time without using the let keyword ((num = num + 1)) # This time we use doublebrackets



<lang Ursala>#import nat

instring = ~&h+ %nP+ successor+ %np@iNC # convert, do the math, convert back</lang> test program: <lang Ursala>#cast %sL

tests = instring* <'22435','4','125','77','325'></lang> output:


Vedit macro language

This example increments numeric string by converting it into numeric value, as most other language examples do. The string is located in text register 10. <lang vedit>itoa(atoi(10)+1, 10)</lang>

The following example increments unsigned numeric string of unlimited length. The current line in the edit buffer contains the string. <lang vedit>EOL do {

   if (At_BOL) {

Ins_Char('1') // add new digit Break

   #1 = Cur_Char+1		// digit
   #2 = 0			// carry bit
   if (#1 > '9') {

#1 = '0' #2 = 1

   Ins_Char(#1, OVERWRITE)

} while (#2) // repeat until no carry</lang>