Increment a numerical string

From Rosetta Code

Jump to: navigation, search
Task
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.

Contents

[edit] ActionScript

function incrementString(str:String):String
{
return String(Number(str)+1);
}

[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] ALGOL 68

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

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))

Output:

     +12346

[edit] AutoHotkey

str = 12345
MsgBox % str += 1

Output:

12346

[edit] AutoIt

Global $x = "12345"
$x += 1
MsgBox(0,"",$x)

Output:

12346

[edit] AWK

The example shows that the string s can be incremented, but after that still is a string of length 2.

$ gawk 'BEGIN{s="42";s++;print s"("length(s)")"}'
43(2)


[edit] BASIC

Works with: QBasic

Works with: PowerBASIC

Works with: Visual Basic

Works with: Liberty BASIC

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

[edit] Batch File

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

Works with: Windows NT version 4

set s=12345
set /a s+=1

[edit] C

#include <stdio.h>
#include <stdlib.h>
#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)
{
test("0");
test("1");
test("-1");
test("1000000000");
test("-1000000000");
 
return 0;
}

Output:

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

[edit] C++

Library: STL

// STL with string stream operators
#include <cstdlib>
#include <string>
#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();

Library: Boost

// Boost
#include <cstdlib>
#include <string>
#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);

Library: Qt

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

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] Clojure

(str (inc (Integer/parseInt "1234")))

[edit] Common Lisp

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

[edit] D

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

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

import tango.text.convert.Integer;

[edit] E

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

[edit] Erlang

integer_to_list(list_to_integer("1336")+1).

[edit] Factor

"1234" string>number 1 + number>string

[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] Fortran

Works with: Fortran version 90 and later Using 'internal' files you can increment both integer and real strings

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

[edit] Go

package main
import "fmt"
import "strconv"
func main() {
i, _ := strconv.Atoi("1234")
fmt.Println(strconv.Itoa(i + 1))
}

[edit] Groovy

Solution:

println ((("23455" as BigDecimal) + 1) as String)
println ((("23455.78" as BigDecimal) + 1) as String)

Output:

23456
23456.78

[edit] Haskell

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


[edit] HicEst

CHARACTER string = "123     -4567.89"
 
READ( Text=string) a, b
WRITE(Text=string) a+1, b+1 ! 124 -4566.89

[edit] 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.

[edit] Icon

s := "123"  # s is a string
s +:= 1# s is now an integer

[edit] Unicon

This Icon solution works in Unicon.

[edit] IDL

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

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

print, '1234' + 1
;==> 1235

[edit] J

incrTextNum=: >:&.".

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.

   incrTextNum '34.5'
35.5
incrTextNum '7 0.2 3r5 2j4 5.7e_4'
8 1.2 1.6 3j4 1.00057

[edit] Java

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.

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

[edit] JavaScript

var s = "12345";
var i = parseInt(s, 10) + 1;
s = i.toString();

A faster way instead of parseInt:

var i = (+s)+1;
s = i.toString()

[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] Logo

Logo is weakly typed, so numeric strings can be treated as numbers and numbers can be treated as strings.

show "123 + 1  ; 124
show word? ("123 + 1) ; true

[edit] Lua

print(tonumber("2345")+1)

[edit] M4

M4 can handle only integer signed 32 bit numbers, and they can be only written as strings

define(`V',`123')dnl
define(`VN',`-123')dnl
eval(V+1)
eval(VN+1)

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)

[edit] Mathematica

Print[FromDigits["1234"] + 1]

[edit] MAXScript

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

[edit] Metafont

string s;
s := "1234";
s := decimal(scantokens(s)+1);
message s;

[edit] Modula-3

Modula-3 provides the module Scan for lexing.

MODULE StringInt EXPORTS Main;
 
IMPORT IO, Fmt, Scan;
 
VAR string: TEXT := "1234";
num: INTEGER := 0;
 
BEGIN
num := Scan.Int(string);
IO.Put(string & " + 1 = " & Fmt.Int(num + 1) & "\n");
END StringInt.

Output:

1234 + 1 = 1235

[edit] MUMPS

Just add.

 
SET STR="123"
WRITE STR+1
 

[edit] Objective-C

NSString *s = @"12345";
int i = [s intValue] + 1;
s = [NSString stringWithFormat:@"%i", i]

[edit] Objeck

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

[edit] OCaml

string_of_int (succ (int_of_string "1234"))

[edit] Octave

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

nstring = "123";
nstring = sprintf("%d", str2num(nstring) + 1);
disp(nstring);

[edit] Oz

{Int.toString {String.toInt "12345"} + 1}

[edit] Perl

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

[edit] Perl 6

Works with: Rakudo version #22 "Thousand Oaks"

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

[edit] PHP

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

[edit] PicoLisp

(format (inc (format "123456")))

[edit] PL/I

 
declare s picture '999999999';
s = '123456789';
s = s + 1;
put skip list (s);
 

[edit] plainTeX

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

The generated page will contain the text:

The number 12345 is followed by 12346.

[edit] Pop11

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

[edit] PowerShell

The easiest way is to cast the string to int, incrementing it and casting back to string:

$s = "12345"
$t = [string] ([int] $s + 1)

One can also take advantage of the fact that PowerShell casts automatically according to the left-most operand to save one cast:

$t = [string] (1 + $s)

[edit] PureBasic

string$="12345"
string$=Str(Val(string$)+1)
Debug string$

[edit] Python

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

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

[edit] R

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

[edit] REBOL

rebol [
Title: "Increment Numerical String"
Author: oofoe
Date: 2009-12-23
URL: http://rosettacode.org/wiki/Increment_numerical_string
]

 
; 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]

Output:

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

[edit] Ruby

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

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

[edit] Scala

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

implicit def toSucc(s: String) = new { def succ = BigDecimal(s) + 1 toString }

Usage:

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

[edit] Scheme

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

[edit] Seed7

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

[edit] Slate

((Integer readFrom: '123') + 1) printString

[edit] Smalltalk

('123' asInteger + 1) printString

[edit] SNOBOL4

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

Input

123

Output

124
124

[edit] Standard ML

Int.toString (1 + valOf (Int.fromString "1234"))

[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] TI-89 BASIC

string(expr(str)+1)

[edit] Toka

" 100" >number drop 1 + >string

[edit] Ursala

#import nat
 
instring = ~&h+ %nP+ successor+ %np@iNC # convert, do the math, convert back

test program:

#cast %sL
 
tests = instring* <'22435','4','125','77','325'>

output:

<'22436','5','126','78','326'>


[edit] 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.

itoa(atoi(10)+1, 10)

The following example increments unsigned numeric string of unlimited length. The current line in the edit buffer contains the string.

EOL
do {
if (At_BOL) {
Ins_Char('1') // add new digit
Break
}
Char(-1)
#1 = Cur_Char+1 // digit
#2 = 0 // carry bit
if (#1 > '9') {
#1 = '0'
#2 = 1
}
Ins_Char(#1, OVERWRITE)
Char(-1)
} while (#2) // repeat until no carry
Personal tools
Support