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.
[edit] 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.
Output
"0" + 1 = "1 " "1" + 1 = "2 " "-1" + 1 = "0 " "10000000" + 1 = "10000001 " "-10000000" + 1 = "9999999-"
[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] Aime
o_text(itoa(atoi("2047") + 1));
o_byte('\n');
[edit] ALGOL 68
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.
$ awk 'BEGIN{s="42";s++;print s"("length(s)")"}'
43(2)
[edit] BASIC
s$ = "12345"
s$ = STR$(VAL(s$) + 1)
[edit] ZX Spectrum Basic
The ZX Spectrum needs line numbers and a let statement, but the same technique can be used:
10 LET s$ = "12345"
20 LET s$ = STR$(VAL(s$) + 1)
[edit] Batch File
Since environment variables have no type distinction all numbers are simply numeric strings:
set s=12345
set /a s+=1
[edit] Boo
s = "1234"
s = (int.Parse(s) + 1).ToString()
[edit] Bracmat
Numbers are strings. Bracmat supports rational numbers, including integers, using arbitrary-precision arithmetic. Pure imaginary numbers are formed using a factor i (or -i). There is no support for floating point arithmetics. (Historically, because the ARM 2 processor in the Archimedes computer didn't sport an FPU.)
(n=35664871829866234762187538073934873121878/6172839450617283945)
&!n+1:?n
&out$!n
35664871829866234762193710913385490405823/6172839450617283945
[edit] Brat
#Convert to integer, increment, then back to string
p ("100".to_i + 1).to_s #Prints 101
[edit] C
Handling strings of arbitrary sizes:#include <stdio.h>output
#include <string.h>
#include <stdlib.h>
/* Constraints: input is in the form of (\+|-)?[0-9]+
* and without leading zero (0 itself can be as "0" or "+0", but not "-0");
* input pointer is realloc'able and may change;
* if input has leading + sign, return may or may not keep it.
* The constranits conform to sprintf("%+d") and this function's own output.
*/
char * incr(char *s)
{
int i, begin, tail, len;
int neg = (*s == '-');
char tgt = neg ? '0' : '9';
/* special case: "-1" */
if (!strcmp(s, "-1")) {
s[0] = '0', s[1] = '\0';
return s;
}
len = strlen(s);
begin = (*s == '-' || *s == '+') ? 1 : 0;
/* find out how many digits need to be changed */
for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);
if (tail < begin && !neg) {
/* special case: all 9s, string will grow */
if (!begin) s = realloc(s, len + 2);
s[0] = '1';
for (i = 1; i <= len - begin; i++) s[i] = '0';
s[len + 1] = '\0';
} else if (tail == begin && neg && s[1] == '1') {
/* special case: -1000..., so string will shrink */
for (i = 1; i < len - begin; i++) s[i] = '9';
s[len - 1] = '\0';
} else { /* normal case; change tail to all 0 or 9, change prev digit by 1*/
for (i = len - 1; i > tail; i--)
s[i] = neg ? '9' : '0';
s[tail] += neg ? -1 : 1;
}
return s;
}
void string_test(const char *s)
{
char *ret = malloc(strlen(s));
strcpy(ret, s);
printf("text: %s\n", ret);
printf(" ->: %s\n", ret = incr(ret));
free(ret);
}
int main()
{
string_test("+0");
string_test("-1");
string_test("-41");
string_test("+41");
string_test("999");
string_test("+999");
string_test("109999999999999999999999999999999999999999");
string_test("-100000000000000000000000000000000000000000000");
return 0;
}
text: +0
->: +1
text: -1
->: 0
text: -41
->: -40
text: +41
->: +42
text: 999
->: 1000
text: +999
->: 1000
text: 109999999999999999999999999999999999999999
->: 110000000000000000000000000000000000000000
text: -100000000000000000000000000000000000000000000
->: -99999999999999999999999999999999999999999999
[edit] C++
// standard C++ 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();
#include <string>
std::string s = "12345";
s = std::to_string(1+std::stoi(s));
// 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);
// Qt
QString num1 = "12345";
QString num2 = QString("%1").arg(v1.toInt()+1);
// 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:
#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";
s = (int.Parse(s) + 1).ToString();
[edit] Clojure
(str (inc (Integer/parseInt "1234")))
[edit] CMake
CMake performs all arithmetic with numeric strings, through its math() command.
set(string "1599")
math(EXPR string "${string} + 1")
message(STATUS "${string}")
-- 1600
[edit] Common Lisp
(princ-to-string (1+ (parse-integer "1234")))
[edit] D
import std.string;
void main() {
string s = succ("12345");
}
[edit] Delphi
program IncrementNumericalString;
{$APPTYPE CONSOLE}
uses SysUtils;
const
STRING_VALUE = '12345';
begin
WriteLn(Format('"%s" + 1 = %d', [STRING_VALUE, StrToInt(STRING_VALUE) + 1]));
Readln;
end.
Output:
"12345" + 1 = 123456
[edit] DWScript
var value : String = "1234";
value := IntToStr(StrToInt(value) + 1);
PrintLn(value);
[edit] E
__makeInt("1234", 10).next().toString(10)
[edit] Erlang
integer_to_list(list_to_integer("1336")+1).
[edit] Euphoria
include get.e
function val(sequence s)
sequence x
x = value(s)
return x[2]
end function
sequence s
s = "12345"
s = sprintf("%d",{val(s)+1})
[edit] Factor
"1234" string>number 1 + number>string
[edit] Fantom
Within 'fansh':
fansh> a := "123"
123
fansh> (a.toInt + 1).toStr
124
[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
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] F#
let next = string( int( "1234" ) + 1 )
[edit] GAP
# Using built-in functions
Incr := s -> String(Int(s) + 1);
# Implementing addition
# (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;
fi;
if c > 9 then
carry := true;
c := c - 10;
else
carry := false;
fi;
s[n] := digits[c + 1];
n := n - 1;
od;
end;
s := "2399";
Increment(s);
s;
# "2400"
[edit] Go
Concise:
package main
import "fmt"
import "strconv"
func main() {
i, _ := strconv.Atoi("1234")
fmt.Println(strconv.Itoa(i + 1))
}
More:
package main
import (
"big"
"fmt"
"strconv"
)
func main() {
// integer
is := "1234"
fmt.Println("original: ", is)
i, err := strconv.Atoi(is)
if err != nil {
fmt.Println(err)
return
}
// assignment back to original variable shows result is the same type.
is = strconv.Itoa(i + 1)
fmt.Println("incremented:", is)
// error checking worthwhile
fmt.Println()
_, err = strconv.Atoi(" 1234") // whitespace not allowed
fmt.Println(err)
_, err = strconv.Atoi("12345678901")
fmt.Println(err)
_, err = strconv.Atoi("_1234")
fmt.Println(err)
_, err = strconv.Atof64("12.D34")
fmt.Println(err)
// float
fmt.Println()
fs := "12.34"
fmt.Println("original: ", fs)
f, err := strconv.Atof64(fs)
if err != nil {
fmt.Println(err)
return
}
// various options on Ftoa64 produce different formats. All are valid
// input to Atof64, so result format does not have to match original
// format. (Matching original format would take a lot of code.)
fs = strconv.Ftoa64(f+1, 'g', -1)
fmt.Println("incremented:", fs)
fs = strconv.Ftoa64(f+1, 'e', 4)
fmt.Println("what format?", fs)
// complex
// strconv package doesn't handle complex types, but fmt does.
// (fmt can be used on ints and floats too, but strconv is more efficient.)
fmt.Println()
cs := "(12+34i)"
fmt.Println("original: ", cs)
var c complex128
_, err = fmt.Sscan(cs, &c)
if err != nil {
fmt.Println(err)
return
}
cs = fmt.Sprint(c + 1)
fmt.Println("incremented:", cs)
// big integers have their own functions
fmt.Println()
bs := "170141183460469231731687303715884105728"
fmt.Println("original: ", bs)
var b, one big.Int
_, ok := b.SetString(bs, 10)
if !ok {
fmt.Println("big.SetString fail")
return
}
one.SetInt64(1)
bs = b.Add(&b, &one).String()
fmt.Println("incremented:", bs)
}
Output:
original: 1234 incremented: 1235 parsing " 1234": invalid argument parsing "12345678901": numerical result out of range parsing "_1234": invalid argument parsing "12.D34": invalid argument original: 12.34 incremented: 13.34 what format? 1.3340e+01 original: (12+34i) incremented: (13+34i) original: 170141183460469231731687303715884105728 incremented: 170141183460469231731687303715884105729
[edit] Golfscript
~)`
With a test framework to supply a number:
"1234" ~)` p
[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.
s := "123" # s is a string
s +:= 1# s is now an integer
[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] 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).
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.
[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
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:
|.incrTextNum'123 456'
754 421
|.1+123 456
457 124
[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 = String.valueOf(Integer.parseInt(s) + 1);
[edit] JavaScript
var s = "12345";
s = (Number(s) + 1).toString();
[edit] K
"." is a built-in function that evaluates a valid K expression.
1 + ."1234"
1235
1 + ."1234.56"
1235.56
/ As a function
inc:{1 + . x}
inc "1234"
1235
Some other examples.
1 + .:' ("1";"2";"3";"4")
2 3 4 5
1 + . "123 456"
124 457
. "1","+","-10"
-9
[edit] LabVIEW
This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.
[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] Liberty BASIC
' [RC] Increment a numerical string.
o$ ="12345"
print o$
v =val( o$)
o$ =str$( v +1)
print o$
end
[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] Logtalk
number_chars(Number, "123"), Number2 is Number+1, number_chars(Number2, String2)
[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] MATLAB
function numStr = incrementNumStr(numStr)
numStr = num2str(str2double(numStr) + 1);
end
[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-2
MODULE addstr;
IMPORT InOut, NumConv, Strings;
VAR str1, str2 : Strings.String;
num : CARDINAL;
ok : BOOLEAN;
BEGIN
str1 := "12345";
InOut.Write ('"'); InOut.WriteString (str1); InOut.WriteString ('" + 1 = ');
NumConv.Str2Num (num, 10, str1, ok);
INC (num);
NumConv.Num2Str (num, 10, str2, ok);
InOut.WriteString (str2);
InOut.WriteLn
END addstr.
"12345" + 1 = 12346
[edit] Nemerle
mutable str = "12345";
str = $"$(Int32.Parse(str)+1)";
[edit] Oberon-2
MODULE addstr;
IMPORT Out, Strings;
VAR str1, str2 : ARRAY 9 OF CHAR;
num, pos : INTEGER;
carry : BOOLEAN;
ch : CHAR;
BEGIN
str1 := "9999";
Out.Char ('"'); Out.String (str1); Out.String ('" + 1 = ');
num := Strings.Length (str1) - 1;
pos := num;
IF str1 [0] = '9' THEN INC (pos) END;
str2 [pos + 1] := 0X;
carry := TRUE;
REPEAT
ch := str1 [num];
IF carry THEN
ch := CHR (ORD (ch) + 1)
END;
IF ch > '9' THEN
carry := TRUE;
ch := '0'
ELSE
carry := FALSE
END;
str2 [pos] := ch;
DEC (num);
DEC (pos)
UNTIL num < 0;
IF carry THEN str2 [0] := '1' END;
Out.String (str2);
Out.Ln
END addstr.
Producing:
jan@Beryllium:~/Oberon/obc$ Add "12345" + 1 = 12346 "9999" + 1 = 10000
[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] NetRexx
In concert with Rexx, NetRexx can use typeless variables. Typeless variable support is provided through the default NetRexx Rexx object. Values 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.
/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
numbers = '12345'
say numbers
numbers = numbers + 1
say numbers
return
- Output
12345 12346
[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] OpenEdge/Progress
DEFINE VARIABLE cc AS CHARACTER INITIAL "12345".
MESSAGE
INTEGER( cc ) + 1
VIEW-AS ALERT-BOX.
[edit] Oz
{Int.toString {String.toInt "12345"} + 1}
[edit] PARI/GP
foo(s)=Str(eval(s)+1);
[edit] Pascal
See Delphi
[edit] Perl
my $s = "12345";
$s++;
[edit] Perl 6
my $s = "12345";
$s++;
[edit] PHP
$s = "12345";
$s++;
[edit] PicoLisp
(format (inc (format "123456")))
[edit] Pike
string number = "0";
number = (string)((int)number+1);
Result: "1"
[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] Prolog
Works with SWI-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).
Output :
?- incr_numerical_string("123", S2).
S2 = "124".
[edit] PureBasic
string$="12345"
string$=Str(Val(string$)+1)
Debug string$
[edit] Python
next = str(int('123') + 1)
[edit] R
s = "12345"
s <- as.character(as.numeric(s) + 1)
[edit] Rascal
import String;
public str IncrNumStr(str s) = "<toInt(s) + 1>";
An example output:
rascal>IncrNumStr("123")
str: "124"
[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] Retro
"123" toNumber 1+ toString
[edit] REXX
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.
count = "3" /* Typeless variables are all strings */
count = count + 1 /* Variables in a numerical context are treated as numbers */
say count
[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] Sed
Reads a decimal integer from stdin and outputs the same with the magnitude incremented by one.
(TODO: Since it deals only with the magnitude, the result is incorrect for negative numbers—though adding this support is definitely possible.)
The routine starts by suffixing the input number with a carry mark (a : in this case) indicating that the digit to its left still needs to be incremented. In a loop, the following happens:
- If there is a carry mark on the far left, replace it with a 1.
- If there are no more carry marks, exit the loop.
- Hold the current number. (
h) - Extract the digit to the left of the first carry mark. (
s) - Replace the digit with the same digit incremented by one, with 9 incrementing to a carry mark (i.e. 10). (
y) - If the result of such replacement was a carry mark, suffix the mark with a 0, indicating that the digit has rolled over and the digit to the left must be incremented. (
s) - Retrieve the held number (
G) and replace the first carry mark and the digit to its left with the result of the computation. (s) - Repeat. (
b)
s/^.*$/&:/
:bubble
s/^:/1/
/.:/ {
h
s/^.*\(.\):.*$/\1/
y/0123456789/123456789:/
s/:/:0/
G
s/\(.*\)\n\(.*\).:\(.*\)$/\2\1\3/
b bubble
}
[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] TUSCRIPT
$$ MODE TUSCRIPT
teststring="0'1'-1'12345'10000000'-10000000"
LOOP/CLEAR n=teststring
n=n+1
PRINT n
ENDLOOP
Output:
1 2 0 12346 10000001 -9999999
[edit] TXR
Two implementations of what the task says: incrementing a numerical string. (Not: converting a string to a number, then incrementing the number, then converting back to string.)
[edit] TXR Lisp
@(do (defun inc-num-str (str-in)
(let ((len (length str-in))
(str (copy-str str-in)))
(for ((i (- len 1)))
((>= i 0) `1@str`)
((dec i))
(if (<= (inc [str i]) #\9)
(return str)
(set [str i] #\0))))))
@(bind a @(inc-num-str "9999"))
@(bind b @(inc-num-str "1234"))
$ ./txr incnum.txr a="10000" b="1235"
[edit] No TXR Lisp
@(deffilter incdig ("0" "1") ("1" "2") ("2" "3") ("3" "4") ("4" "5")
("5" "6") ("6" "7") ("7" "8") ("8" "9"))
@(define increment (num out))
@ (local prefix dig junk)
@ (next :string num)
@ (cases)
9
@ (bind out "10")
@ (or)
@*{prefix}@{dig /[0-8]/}
@ (bind out `@prefix@{dig :filter incdig}`)
@ (or)
@*{prefix}9
@ (bind out `@{prefix :filter (:fun increment)}0`)
@ (or)
@junk
@ (throw error `bad input: @junk`)
@ (end)
@(end)
@in
@(increment in out)
$ echo 1 | ./txr incnum.txr - input="1" result="2" $ echo 123 | ./txr incnum.txr - input="123" result="124" $ echo 899999 | ./txr incnum.txr - input="899999" result="900000" $ echo 999998 | ./txr incnum.txr - input="999998" result="999999" $ echo 999999 | ./txr incnum.txr - input="999999" result="1000000"
[edit] UNIX Shell
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:
# All variables are strings within the shell
# Although num look like a number, it is in fact a numerical string
num=5
num=`expr $num + 1` # Increment the number
The Korn Shell and some newer shells do support arithmetic operations directly, and several syntax options are available:
num=5
let num=num+1 # Increment the number
let "num = num + 1" # Increment again. (We can use spaces inside quotes)
((num = num + 1)) # This time we use doublebrackets
let num+=1 # This time we use +=
let "num += 1"
((num += 1))
integer num=5 # Declare an integer...
num=$num+1 # ...then increment without the let keyword.
[edit] C Shell
The @ assignment command uses strings as integers.
@ num = 5
@ num += 1
[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
[edit] VBA
The easy method assumes that the number can be represented as a Long integer:
Public Function incr(astring As String) As String
'simple function to increment a number string
incr = CStr(CLng(astring) + 1)
End Function
Examples:
print incr("345343434")
345343435
print incr("-10000000")
-9999999
The long version handles arbitrary-length strings:
Public Function Lincr(astring As String) As String
'increment a number string, of whatever length
'calls function "increment" or "decrement"
Dim result As String
'see if it is a negative number
If left$(astring, 1) = "-" Then
'negative x: decrease |x| by 1, then add "-"
'(except if the result is zero)
result = decrement(Mid$(astring, 2))
If result <> "0" Then result = "-" & result
Else
'0 or positive x: increase x by 1
If left$(astring, 1) = "+" Then 'allow a + before the number
result = increment(Mid$(astring, 2))
Else
result = increment(astring)
End If
End If
Lincr = result
End Function
Public Function increment(astring) As String
Dim result As String
'increment a string representing a positive number
'does not work with negative numbers
carry = 1
L = Len(astring)
result = ""
For j = L To 1 Step -1
digit = Val(Mid$(astring, j, 1)) + carry
If digit > 9 Then
digit = digit - 10
carry = 1
Else
carry = 0
End If
result = CStr(digit) & result
Next
If carry = 1 Then result = CStr(carry) & result
increment = result
End Function
Public Function decrement(astring) As String
Dim result As String
'decrement a string representing a positive number
'does not work with zero or negative numbers
borrow = 1
L = Len(astring)
result = ""
For j = L To 1 Step -1
digit = Val(Mid$(astring, j, 1)) - borrow
If digit < 0 Then
digit = digit + 10
borrow = 1
Else
borrow = 0
End If
result = CStr(digit) & result
Next
'remove leading zero, if necessary
If (Len(result) > 1) And (left$(result, 1) = "0") Then result = Mid$(result, 2)
decrement = result
End Function
Examples:
print Lincr("99999999999999999")
100000000000000000
print Lincr("-10000000000000000")
-9999999999999999
print Lincr("-1")
0
print Lincr("0")
1
print Lincr("+1234567890987654321009")
1234567890987654321010
[edit] Visual Basic .NET
Dim s As String = "123"
s = CStr(CInt("123") + 1)
' or
s = (CInt("123") + 1).ToString
- Programming Tasks
- Text processing
- ABAP
- ActionScript
- Ada
- Aime
- ALGOL 68
- AutoHotkey
- AutoIt
- AWK
- BASIC
- ZX Spectrum Basic
- Batch File
- Boo
- Bracmat
- Brat
- C
- C++
- Boost
- Qt
- MFC
- Microsoft Foundation Classes
- C Runtime
- C sharp
- Clojure
- CMake
- Common Lisp
- D
- Delphi
- DWScript
- E
- Erlang
- Euphoria
- Factor
- Fantom
- Forth
- Fortran
- F Sharp
- GAP
- Go
- Golfscript
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- IDL
- Inform 7
- J
- Java
- JavaScript
- K
- LabVIEW
- LaTeX
- Liberty BASIC
- Logo
- Logtalk
- Lua
- M4
- Mathematica
- MATLAB
- MAXScript
- Metafont
- Modula-2
- Nemerle
- Oberon-2
- Modula-3
- MUMPS
- Objective-C
- NetRexx
- Objeck
- OCaml
- Octave
- OpenEdge/Progress
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PL/I
- PlainTeX
- Pop11
- PowerShell
- Prolog
- PureBasic
- Python
- R
- Rascal
- REBOL
- Retro
- REXX
- Ruby
- Scala
- Scheme
- Sed
- Seed7
- Slate
- Smalltalk
- SNOBOL4
- Standard ML
- Tcl
- TI-89 BASIC
- Toka
- TUSCRIPT
- TXR
- UNIX Shell
- C Shell
- Ursala
- Vedit macro language
- VBA
- Visual Basic .NET