# Increment a numerical string

You are encouraged to solve this task according to the task description, using any language you may know.

Increment a numerical string.

## 11l

Translation of: Python
V next = String(Int(‘123’) + 1)

## 8080 Assembly

	org	100h
jmp	demo
;;; Increment the number in the $-terminated string under HL. ;;; The new string is written back to the original location. ;;; It may grow by one byte (e.g. 999 -> 1000). incstr: mvi a,'$'	; End marker
lxi	d,303Ah	; D='0', E='9'+1
lxi	b,0	; Find the end of the string and find the length
isrch:	cmp	m	; Are we there yet?
inx	b	; If not, try next character
inx	h
jnz	isrch
dcx	h
dcx	b
mov	a,b	; Is the string empty?
ora	c
rz		; Then return (do nothing)
inx	b
idigit:	dcx	b	; Go to previous digit
dcx	h
mov	a,b	; Are we at the beginning of the string?
ora	c
jz	igrow	; Then the string grows (999 -> 1000)
inr 	m	; Otherwise, increment the digit
mov	a,e
cmp	m	; Did we try to increment '9'?
rnz		; If not, we're done, return
mov	m,d	; But if so, this digit is now a 0
jmp	idigit	; And we should do the next digit
igrow:	inx	h
mvi	m,'1'	; The string should now be '10000...'
inx	h	; We know the string is at least one char long
mvi	a,'$' izero: cmp m ; Are we at the end yet? mov m,d ; In any case, write a zero inx h jnz izero ; If not done, write a zero mov m,a ; Finally, reterminate the string ret ;;; Demo code: increment the CP/M command line argument demo: lxi h,80h ;$-terminate the string
mov	a,m
adi	81h	; Length is at 80h, the argument itself at 81h
mov	l,a
mvi	m,'$' mvi l,80h ; Skip any spaces mvi a,' ' space: inx h cmp m jz space push h ; Store the beginning of the string call incstr ; Increment the number in the string pop d ; Print the string mvi c,9 jmp 5 ## 8086 Assembly  cpu 8086 bits 16 section .text org 100h jmp demo ; Jump towards demo code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Increment the number in the$-terminated string
;;;	in [ES:DI]. The string is written back to its original
;;;	location. It may grow by one byte.
incnum:	mov	al,'$' ; Find string terminator mov bx,di ; Store the beginning of the string mov cx,-1 repne scasb dec di ; Move to the terminator cmp bx,di ; If the string is empty, do nothing je .out .digit: cmp bx,di ; Is this the first digit? je .grow ; If so, the string grows dec di ; Go one digit backwards inc byte [es:di] ; Increment the digit cmp byte [es:di],'9'+1 ; Did we increment past 9? jne .out ; If not, we're done mov byte [es:di],'0' ; Otherwise, write a zero jmp .digit ; And increment the next digit .grow: mov al,'1' ; Write an 1 first (we know the string stosb ; is at least one character long) dec al ; Zero .zero: cmp byte [es:di],'$'	; Are we about to overwrite
stosb			; the terminator? First, do it anyway;
jne	.zero		; Keep writing zeroes until $is reached mov al,'$'		; Finally, write a new terminator
stosb
.out:	ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;	Demo code: increment the number on the MS-DOS
;;;	command line.
demo:	mov	si,80h		; $-terminate the string lodsb xor bh,bh mov bl,al mov byte [si+bx],'$'
mov	al,' '		; Skip past any spaces
mov	cx,-1
mov	di,si
repe	scasb
dec	di
mov	dx,di		; Keep start of string in DX
call	incnum		; Increment the number in the string
mov	ah,9		; Print the string
int	21h
ret


## AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program incstring64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ BUFFERSIZE,   100
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessNum:           .asciz "Enter number : \n"
szCarriageReturn:    .asciz "\n"
szMessResult:        .asciz "Increment number is =  @ \n"      // message result

/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
sBuffer:    .skip BUFFERSIZE
sZoneConv:  .skip 24
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:                      // entry of program

bl affichageMess
mov x0,#STDIN          // Linux input console
mov x2,#BUFFERSIZE     // buffer size
svc 0                  // call system
strb wzr,[x1,x0]       // store zero at the end of input string (x0
//
bl conversionAtoD      // conversion string in number in x0
// increment x0
// conversion register to string
bl conversion10S       // call conversion
bl strInsertAtCharInc  // insert result at @ character
bl affichageMess       // display message

100:                       // standard end of the program
mov x0,0               // return code
mov x8,EXIT            // request to exit program
svc 0                  // perform the system call

/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
Output:
Enter number :
50
Increment number is =  +51
pi@debian-buster-64:~/asm64/rosetta/asm4 incstring64 Enter number : -12 Increment number is = -11  ## 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-"  ## Action! PROC Increment(CHAR ARRAY src,dst) INT val val=ValI(src) val==+1 StrI(val,dst) RETURN PROC Test(CHAR ARRAY src) CHAR ARRAY dst(10) Increment(src,dst) PrintF("%S+1=%S%E",src,dst) RETURN PROC Main() Test("0") Test("1") Test("9999") Test("-1") Test("-2") Test("-10000") RETURN Output: 0+1=1 1+1=2 9999+1=10000 -1+1=0 -2+1=-1 -10000+1=-9999  ## ActionScript function incrementString(str:String):String { return String(Number(str)+1); }  ## 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);  ## Aime o_text(itoa(atoi("2047") + 1)); o_byte('\n'); ## 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  ## ALGOL W Increments a string representaton of an integer, without converting it to an integer and so allows values greater than will fit into an Algol W integer (which is restricted to 32 bits). begin % returns a string representing the number in s incremented % % As strings are fixed length, the significant length of s must % % be specified in length % % s must contain an unsigned integer % % If the string is invalid or the result would require more % % than 256 characters (the maximum string length), "error" % % is returned % string(256) procedure increment( string(256) value s ; integer value length ) ; begin logical isValid; integer rPos, sPos, carry; string(256) iValue; string(1) c; isValid := true; iValue := " "; rPos := 256; sPos := length - 1; carry := 1; % ensure the first digit is incremented % while isValid and sPos >= 0 and rPos >= 0 do begin c := s( sPos // 1 ); sPos := sPos - 1; if c not = " " then begin isValid := ( c >= "0" and c <= "9" ); if isValid then begin integer d; d := ( decode( c ) - decode( "0" ) ) + carry; carry := d div 10; rPos := rPos - 1; iValue( rPos // 1 ) := code( decode( "0" ) + d rem 10 ) end if_isValid end if_c_ne_space end while_isValid_and_sPos_ge_0_and_rPOs_ge_0 ; if isValid then begin % the number was incremented successfully % if carry not = 0 then begin % need an extra digit % if rPos <= 0 then isValid := false % no room for an extra digit % else begin % have space for an extra digit % rPos := rPos - 1; iValue( rPos // 1 ) := code( decode( "0" ) + carry ) end if_rPos_lt_0__ end if_carry_gt_0 end if_isValid ; if not isValid then begin % s is not a numeric string or the result would be longer than 256 characters % iValue := "error" end else begin % the string could be incremented % string(256) rightJustifiedValue; rightJustifiedValue := iValue; iValue := " "; for iPos := 0 until 255 - rPos do iValue( iPos // 1 ) := rightJustifiedValue( rPos + iPos // 1 ) end if_not_isValid_or_carry_ne_0__ ; iValue end increment ; % writes the string s, up to the first blank % procedure writeonToBlank ( string(256) value s ) ; begin integer sPos; sPos := 0; while sPos < 256 and s( sPos // 1 ) not = " " do begin writeon( s_w := 0, s( sPos // 1 ) ); sPos := sPos + 1 end while_spos_lt_256_and_s_Spos_ne_space end writeonToBlank ; % test increment % write( " 0 + 1: " ); writeonToBlank( increment( "0", 1 ) ); write( " 9 + 1: " ); writeonToBlank( increment( "9", 1 ) ); write( " 123456789 + 1: " ); writeonToBlank( increment( "123456789", 9 ) ); write( "99999999999999999999 + 1: " ); writeonToBlank( increment( "99999999999999999999", 20 ) ) end. Output:  0 + 1: 1 9 + 1: 10 123456789 + 1: 123456790 99999999999999999999 + 1: 100000000000000000000  ## Apex string count = '12345'; count = String.valueOf(integer.valueOf(count)+1); system.debug('Incremental Value : '+count); Output: 12346 ## APL ⍕1+⍎'12345'  Output: 12346 ## AppleScript ### Functional Preserving the distinction between real and integer strings, and allowing for strings containing non-numeric tokens and/or multiple numeric expressions. Provides an option to either retain or prune out any non-numeric tokens in the string: Translation of: Python Translation of: Haskell Translation of: JavaScript use AppleScript version "2.4" use framework "Foundation" use scripting additions -- succString :: Bool -> String -> String on succString(blnPruned, s) script go on |λ|(w) try if w contains "." then set v to w as real else set v to w as integer end if {(1 + v) as string} on error if blnPruned then {} else {w} end if end try end |λ| end script unwords(concatMap(go, |words|(s))) end succString -- TEST --------------------------------------------------- on run script test on |λ|(bln) succString(bln, ¬ "41 pine martens in 1491.3 -1.5 mushrooms ≠ 136") end |λ| end script unlines(map(test, {true, false})) end run --> 42 1492.3 -0.5 137 --> 42 pine martens in 1492.3 -0.5 mushrooms ≠ 137 -- GENERIC ------------------------------------------------ -- concatMap :: (a -> [b]) -> [a] -> [b] on concatMap(f, xs) set lng to length of xs set acc to {} tell mReturn(f) repeat with i from 1 to lng set acc to acc & |λ|(item i of xs, i, xs) end repeat end tell return acc end concatMap -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn -- unlines :: [String] -> String on unlines(xs) set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set str to xs as text set my text item delimiters to dlm str end unlines -- unwords :: [String] -> String on unwords(xs) set {dlm, my text item delimiters} to ¬ {my text item delimiters, space} set s to xs as text set my text item delimiters to dlm return s end unwords -- words :: String -> [String] on |words|(s) set ca to current application (((ca's NSString's stringWithString:(s))'s ¬ componentsSeparatedByCharactersInSet:(ca's ¬ NSCharacterSet's whitespaceAndNewlineCharacterSet()))'s ¬ filteredArrayUsingPredicate:(ca's ¬ NSPredicate's predicateWithFormat:"0 < length")) as list end |words|  Output: 42 1492.3 -0.5 137 42 pine martens in 1492.3 -0.5 mushrooms ≠ 137 ### AppleScriptObjC The task description's delightfully unforthcoming about what it means by "increment" ("add 1" as in C-related languages or "add a certain amount" as in English?) and what "numerical string" covers with respect to size, number type, format, locale, and base. At its most trivial, given a string representing a modest, unformatted decimal integer, the vanilla AppleScript solution would be: ("12345" + 1) as text --> "12346"  The following handles more possibilities, but the number base is still resolutely decimal: use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later use framework "Foundation" -- Using the machine's own locale setting. The numerical text must be compatible with this. -- Params: Numerical text or NSString, AppleScript or Objective-C number or text equivalent. on incrementNumericalString:str byAmount:increment set localeID to current application's class "NSLocale"'s currentLocale()'s localeIdentifier() return my incrementNumericalString:str byAmount:increment localeID:localeID end incrementNumericalString:byAmount: -- Including the locale ID as an additional parameter. -- Params: As above plus locale ID (text or NSString). on incrementNumericalString:str byAmount:increment localeID:localeID set |⌘| to current application set str to |⌘|'s class "NSString"'s stringWithString:(str) set locale to |⌘|'s class "NSLocale"'s localeWithLocaleIdentifier:(localeID) set decSeparator to locale's objectForKey:(|⌘|'s NSLocaleDecimalSeparator) set regex to |⌘|'s NSRegularExpressionSearch -- Use an NSNumberFormatter to generate the NSDecimalNumber objects for the math, -- as its number/string conversions are more flexible than NSDecimalNumber's own. tell |⌘|'s class "NSNumberFormatter"'s new() its setGeneratesDecimalNumbers:(true) its setLocale:(locale) set symbolRange to str's rangeOfString:("[Ee]| ?[x*] ?10 ?\\^ ?") options:(regex) if (symbolRange's |length|() > 0) then -- Catered-for exponent symbol in the input string. Set the output style to "scientific". its setNumberStyle:(|⌘|'s NSNumberFormatterScientificStyle) its setExponentSymbol:(str's substringWithRange:(symbolRange)) else -- Straight numerical text, with or without separators as per the input and locale. its setNumberStyle:(|⌘|'s NSNumberFormatterDecimalStyle) set groupingSeparator to locale's objectForKey:(|⌘|'s NSLocaleGroupingSeparator) its setUsesGroupingSeparator:(str's containsString:(groupingSeparator)) its setMinimumFractionDigits:(str's containsString:(decSeparator)) end if -- Derive NSDecimalNumbers from the inputs, add together, convert the result back to NSString. set increment to (|⌘|'s class "NSArray"'s arrayWithArray:({increment}))'s firstObject() if ((increment's isKindOfClass:(|⌘|'s class "NSNumber")) as boolean) then ¬ set increment to its stringFromNumber:(increment) set sum to (its numberFromString:(str))'s decimalNumberByAdding:(its numberFromString:(increment)) set output to its stringFromNumber:(sum) end tell -- Adjustments for AppleScript norms the NSNumberFormatter may omit from scientific notation output: if (symbolRange's |length|() > 0) then -- If no decimal separator in the output mantissa, insert point zero or not to match the input style. if ((output's containsString:(decSeparator)) as boolean) then else if ((str's containsString:(decSeparator)) as boolean) then set output to output's stringByReplacingOccurrencesOfString:("(?<=^-?\\d)") ¬ withString:((decSeparator as text) & "0") options:(regex) range:({0, output's |length|()}) end if -- If no sign in an E-notation exponent, insert "+" or not ditto. if (((output's rangeOfString:("[Ee][+-]") options:(regex))'s |length|() > 0) as boolean) then else if (((str's rangeOfString:("[Ee][+-]") options:(regex))'s |length|() > 0) as boolean) then set output to output's stringByReplacingOccurrencesOfString:("(?<=[Ee])") ¬ withString:("+") options:(regex) range:({0, output's |length|()}) end if end if return output as text -- Return as AppleScript text. end incrementNumericalString:byAmount:localeID: return {¬ (my incrementNumericalString:"12345" byAmount:1), ¬ (my incrementNumericalString:"999,999,999,999,999" byAmount:5), ¬ (my incrementNumericalString:"-1.234" byAmount:10 localeID:"en"), ¬ (my incrementNumericalString:"-1,234E+1" byAmount:10 localeID:"fr_FR"), ¬ (my incrementNumericalString:"-1.234 x 10^1" byAmount:"10") ¬ }  Output: (On a machine configured for "en_GB".) {"12346", "1,000,000,000,000,004", "8.766", "-2,34E+0", "-2.34 x 10^0"}  ## ARM Assembly Works with: as version Raspberry Pi /* ARM assembly Raspberry PI */ /* program incstring.s */ /* Constantes */ .equ BUFFERSIZE, 100 .equ STDIN, 0 @ Linux input console .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ READ, 3 @ Linux syscall .equ WRITE, 4 @ Linux syscall /* Initialized data */ .data szMessNum: .asciz "Enter number : \n" szCarriageReturn: .asciz "\n" szMessResult: .ascii "Increment number is = " @ message result sMessValeur: .fill 12, 1, ' ' .asciz "\n" /* UnInitialized data */ .bss sBuffer: .skip BUFFERSIZE /* code section */ .text .global main main: /* entry of program */ push {fp,lr} /* saves 2 registers */ ldr r0,iAdrszMessNum bl affichageMess mov r0,#STDIN @ Linux input console ldr r1,iAdrsBuffer @ buffer address mov r2,#BUFFERSIZE @ buffer size mov r7, #READ @ request to read datas swi 0 @ call system ldr r1,iAdrsBuffer @ buffer address mov r2,#0 @ end of string strb r2,[r1,r0] @ store byte at the end of input string (r0 @ ldr r0,iAdrsBuffer @ buffer address bl conversionAtoD @ conversion string in number in r0 @ increment r0 add r0,#1 @ conversion register to string ldr r1,iAdrsMessValeur bl conversion10S @ call conversion ldr r0,iAdrszMessResult bl affichageMess @ display message 100: /* standard end of the program */ mov r0, #0 @ return code pop {fp,lr} @restaur 2 registers mov r7, #EXIT @ request to exit program swi 0 @ perform the system call iAdrsMessValeur: .int sMessValeur iAdrszMessNum: .int szMessNum iAdrsBuffer: .int sBuffer iAdrszMessResult: .int szMessResult iAdrszCarriageReturn: .int szCarriageReturn /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {fp,lr} /* save registres */ push {r0,r1,r2,r7} /* save others registers */ mov r2,#0 /* counter length */ 1: /* loop length calculation */ ldrb r1,[r0,r2] /* read octet start position + index */ cmp r1,#0 /* if 0 its over */ addne r2,r2,#1 /* else add 1 in the length */ bne 1b /* and loop */ /* so here r2 contains the length of the message */ mov r1,r0 /* address message in r1 */ mov r0,#STDOUT /* code to write to the standard output Linux */ mov r7, #WRITE /* code call system "write" */ swi #0 /* call systeme */ pop {r0,r1,r2,r7} /* restaur others registers */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* return */ /******************************************************************/ /* Convert a string to a number stored in a registry */ /******************************************************************/ /* r0 contains the address of the area terminated by 0 or 0A */ /* r0 returns a number */ conversionAtoD: push {fp,lr} @ save 2 registers push {r1-r7} @ save others registers mov r1,#0 mov r2,#10 @ factor mov r3,#0 @ counter mov r4,r0 @ save address string -> r4 mov r6,#0 @ positive sign by default mov r0,#0 @ initialization to 0 1: /* early space elimination loop */ ldrb r5,[r4,r3] @ loading in r5 of the byte located at the beginning + the position cmp r5,#0 @ end of string -> end routine beq 100f cmp r5,#0x0A @ end of string -> end routine beq 100f cmp r5,#' ' @ space ? addeq r3,r3,#1 @ yes we loop by moving one byte beq 1b cmp r5,#'-' @ first character is - moveq r6,#1 @ 1 -> r6 beq 3f @ then move on to the next position 2: /* beginning of digit processing loop */ cmp r5,#'0' @ character is not a number blt 3f cmp r5,#'9' @ character is not a number bgt 3f /* character is a number */ sub r5,#48 umull r0,r1,r2,r0 @ multiply par factor 10 cmp r1,#0 @ overflow ? bgt 99f @ overflow error add r0,r5 @ add to r0 3: add r3,r3,#1 @ advance to the next position ldrb r5,[r4,r3] @ load byte cmp r5,#0 @ end of string -> end routine beq 4f cmp r5,#0x0A @ end of string -> end routine beq 4f b 2b @ loop 4: cmp r6,#1 @ test r6 for sign moveq r1,#-1 muleq r0,r1,r0 @ if negatif, multiply par -1 b 100f 99: /* overflow error */ ldr r0,=szMessErrDep bl affichageMess mov r0,#0 @ return zero if error 100: pop {r1-r7} @ restaur other registers pop {fp,lr} @ restaur 2 registers bx lr @return procedure /* constante program */ szMessErrDep: .asciz "Too large: overflow 32 bits.\n" .align 4 /***************************************************/ /* Converting a register to a signed decimal */ /***************************************************/ /* r0 contains value and r1 area address */ conversion10S: push {r0-r4,lr} @ save registers mov r2,r1 /* debut zone stockage */ mov r3,#'+' /* par defaut le signe est + */ cmp r0,#0 @ negative number ? movlt r3,#'-' @ yes mvnlt r0,r0 @ number inversion addlt r0,#1 mov r4,#10 @ length area 1: @ start loop bl divisionpar10 add r1,#48 @ digit strb r1,[r2,r4] @ store digit on area sub r4,r4,#1 @ previous position cmp r0,#0 @ stop if quotient = 0 bne 1b strb r3,[r2,r4] @ store signe subs r4,r4,#1 @ previous position blt 100f @ if r4 < 0 -> end mov r1,#' ' @ space 2: strb r1,[r2,r4] @store byte space subs r4,r4,#1 @ previous position bge 2b @ loop if r4 > 0 100: pop {r0-r4,lr} @ restaur registers bx lr /***************************************************/ /* division par 10 signé */ /* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* /* and http://www.hackersdelight.org/ */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10: /* r0 contains the argument to be divided by 10 */ push {r2-r4} /* save registers */ mov r4,r0 ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ add r0, r2, r1 /* r0 <- r2 + r1 */ add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ pop {r2-r4} bx lr /* leave function */ .align 4 .Ls_magic_number_10: .word 0x66666667 ## Arturo num: "12349" print ["The next number is:" (to :integer num)+1]  Output: The next number is: 12350 ## Asymptote string cadena = "12345.78"; cadena = string((real)cadena + 1); write(cadena);  Output: 12346.78 ## AutoHotkey str = 12345 MsgBox % str += 1  Output: 12346 ## AutoIt Globalx = "12345"
$x += 1 MsgBox(0,"",$x)

Output:
12346

## Avail

numberString ::= "1080";
incremented ::= numberString (base 10) + 1;

## 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)  ## BASIC Works with: Applesoft BASIC Works with: BaCon Works with: BBC BASIC Works with: QBasic Works with: PowerBASIC Works with: Visual Basic Works with: Liberty BASIC Works with: Yabasic s$ = "12345"
s$= STR$(VAL(s$) + 1)  ### Applesoft BASIC S$ = "12345":S$= STR$ ( VAL (S$) + 1) ### BASIC256 cadena$ = "12345"
cadena$= string(val(cadena$) + 1)
#or also
cadena$= string(FromRadix(cadena$,10) + 1)

### OxygenBasic

When a number is assigned to a string, it autoconverts.

string s="122"
s=val(s)+1
print s 'result: "123"


### True BASIC

Works with: QBasic
LET cadena$= "12345" LET cadena$ = STR$(VAL(cadena$) + 1)
20 LET s$= STR$(VAL(s$) + 1) ## 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 ## BBC BASIC This assumes the task is about incrementing an arbitrary-length decimal string.  num$ = "567"
REPEAT
PRINT num$PROCinc$(num$) UNTIL FALSE END DEF PROCinc$(RETURN n$) LOCAL A$, I%
I% = LEN(n$) REPEAT A$ = CHR$(ASCMID$(n$,I%) + 1) IF A$=":" A$= "0" MID$(n$,I%,1) = A$
I% -= 1
UNTIL A$<>"0" OR I%=0 IF A$="0" n$= "1" + n$
ENDPROC


## Boo

s = "1234"
s = (int.Parse(s) + 1).ToString()


## BQN

1•Repr∘+•BQN "1234"


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

(n=35664871829866234762187538073934873121878/6172839450617283945)
&!n+1:?n
message(STATUS "${string}")  -- 1600 ## COBOL  PROGRAM-ID. increment-num-str. DATA DIVISION. WORKING-STORAGE SECTION. 01 str PIC X(5) VALUE "12345". 01 num REDEFINES str PIC 9(5). PROCEDURE DIVISION. DISPLAY str ADD 1 TO num DISPLAY str GOBACK .  The following example also increments a numerical string, although it does not apear to. num-str is implicitly defined as USAGE DISPLAY which means its contents will be stored as characters. This means num-str is effectively a string of (numeric) characters.  PROGRAM-ID. increment-num-str. DATA DIVISION. WORKING-STORAGE SECTION. 01 num-str PIC 9(5) VALUE 12345. PROCEDURE DIVISION. DISPLAY num-str ADD 1 TO num-str DISPLAY num-str GOBACK .  ## Common Lisp (princ-to-string (1+ (parse-integer "1234")))  ## Component Pascal BlackBox Component Builder MODULE Operations; IMPORT StdLog,Args,Strings; PROCEDURE IncString(s: ARRAY OF CHAR): LONGINT; VAR resp: LONGINT; done: INTEGER; BEGIN Strings.StringToLInt(s,resp,done); INC(resp); RETURN resp END IncString; PROCEDURE DoIncString*; VAR p: Args.Params; BEGIN Args.Get(p); IF p.argc > 0 THEN StdLog.String(p.args + " + 1= ");StdLog.Int(IncString(p.args));StdLog.Ln END END DoIncString; END Operations. Execute: ^Q Operatiosn.DoIncString 124343~ Output: 124343 + 1= 124344  ## D void main() { import std.string; immutable s = "12349".succ; assert(s == "12350"); }  ## dc ? 1 + p The program expects a string on stdin: echo '12345678899' | dc inc.dc  Output: 12345678900 ## Delphi program IncrementNumericalString; {$APPTYPE CONSOLE}

uses SysUtils;

const
STRING_VALUE = '12345';
begin
WriteLn(Format('"%s" + 1 = %d', [STRING_VALUE, StrToInt(STRING_VALUE) + 1]));

end.

Output:
"12345" + 1 = 123456

## dt

"1234567889" to-int 1 + to-string

## Dyalect

var str = "42"
str = (parse(str) + 1).ToString()

//Another option:
str = (Integer(str) + 1).ToString()

//And another option using interpolation:

## Seed7

var string: s is "12345";

s := str(succ(integer parse s));

## SenseTalk

put "123" + 1  // 124

## SequenceL

import <Utilities/Conversion.sl>;

increment(input(1)) := intToString(stringToInt(input) + 1);

## Sidef

say '1234'.inc;    #=> '1235'
say '99'.inc;      #=> '100'

## Slate

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

## Smalltalk

('123' asInteger + 1) printString

(a note to non-smalltalkers: "printString" does not print, but return the "printString")

## SNOBOL4

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

Output:
124
124


## SparForte

As a structured script.

#!/usr/local/bin/spar
pragma annotate( summary, "incstr" )
@( description, "Increment an integer number in a string" )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/Increment_a_numerical_string" );

pragma software_model( nonstandard );
pragma restriction( no_external_commands );

procedure incstr is
s : string := "12345";
begin
s := strings.trim( strings.image( integer( numerics.value( s ) + 1 ) ), trim_end.both ) ;
? s;
end incstr;

## Sparkling

function numStrIncmt(s) {
return fmtstr("%d", toint(s) + 1);
}

spn:1> numStrIncmt("12345")
= 12346

## SuperTalk

put 0 into someVar
-- without "into [field reference]" the value will appear
-- in the message box
put someVar -- into cd fld 1

## Swift

Works with: Swift version 2.x+
let s = "1234"
if let x = Int(s) {
print("\(x + 1)")
}
Works with: Swift version 1.x
let s = "1234"
if let x = s.toInt() {
println("\(x + 1)")
}

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

## TI-83 BASIC

There is no single command to convert a number to a string; you have to store it to one of the Function variables which acts as both a number and a string.

:"1"→Str1
:expr(Str1)+1→A
:{0,1}→L₁
:{0,A}→L₂
:LinReg(ax+b) Y₁
:Equ►String(Y₁,Str1)
:sub(Str1,1,length(Str1)-3)→Str1

## TI-89 BASIC

string(expr(str)+1)

## Toka

" 100" >number drop 1 + >string

## TorqueScript

To increment by 1:

 $string = "12345";$string++;


$string is now 12346. To increment by more than 1: $string = "12345";
$string += 10; $string is now 12355.

## Transd

(with s "12345"
(= s String((+ (to-Int s) 1))))
(textout s))
Output:
12346


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


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

#### 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 -B incnum.txr a="10000" b="1235" #### 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 -B incnum.txr -
input="1"
result="2"
$echo 123 | ./txr -B incnum.txr - input="123" result="124"$ echo 899999 | ./txr -B incnum.txr -
input="899999"
result="900000"
$echo 999998 | ./txr -B incnum.txr - input="999998" result="999999"$ echo 999999 | ./txr -B incnum.txr -
input="999999"
result="1000000"

## 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:

Works with: Bourne Shell
# 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: Works with: bash Works with: ksh93 Works with: pdksh Works with: zsh 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)) Works with: ksh93 Works with: pdksh Works with: zsh integer num=5 # Declare an integer... num=$num+1             # ...then increment without the let keyword.

### C Shell

The @ assignment command uses strings as integers.

@ num = 5
@ num += 1

## Ursa

decl string num
set num "123"
set num (int (+ (int num) 1))

## 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'>


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



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

## Visual Basic .NET

    Dim s As String = "123"

s = CStr(CInt("123") + 1)
' or
s = (CInt("123") + 1).ToString

## V (Vlang)

// Increment a numerical string in V
module main

// V int conversion will give 0 for nonnumeric strings
pub fn main() {
mut numstr := "-5"
print("numstr: ${numstr:-5} ") numstr = (numstr.int()+1).str() println("numstr:$numstr")

// Run a few tests
for testrun in ["0", "100", "00110", "abc", "41"] {
print("numstr: $testrun ") numstr = (testrun.int()+1).str() println("numstr:$numstr")
}
}
Output:
prompt\$ v run increment-a-numerical-string.v
numstr: -5    numstr: -4
numstr: 0  numstr: 1
numstr: 100  numstr: 101
numstr: 00110  numstr: 111
numstr: abc  numstr: 1
numstr: 41  numstr: 42

## Wren

var ns = "41"
var n = Num.fromString(ns) + 1
var ns2 = "%(n)"
System.print("%(ns) + 1 = %(ns2)")
Output:
41 + 1 = 42


## XLISP

(DEFUN INCREMENT-STRING (X)
(NUMBER->STRING (+ (STRING->NUMBER X) 1)))

## XPL0

string 0;               \use zero-terminated string convention
code Text=12;

func StrLen(A);         \Return number of characters in an ASCIIZ string
char A;
int  I;
for I:= 0 to -1>>1-1 do
if A(I) = 0 then return I;

proc IncStr(S);         \Increment a numeric string
char S;
int  I;
[for I:= StrLen(S)-1 downto 0 do
[S(I):= S(I)+1;
if S(I) > ^9 then S(I):= S(I)-10 else return;
];
];

char Str;
[Str:= "0123999999999"; \MSD first (big endian)
IncStr(Str);  IncStr(Str);
Text(0, Str);
]
Output:
0124000000001


## Z80 Assembly

As a test case, we'll start with 1999 and increment it to 2000.

;;;;;;;;;;;;;;;;;;; HEADER ;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;; PROGRAM  ;;;;;;;;;;;;;;;;;;;

org &1000
ld hl,NumericString

incstring:
ld a,(hl)
cp 255
jr z,displaystring
cp &3A
jr nz,displaystring
;carry forward
ld a,&30
ld (hl),a
inc hl
jr incstring
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
displaystring:
ld (hl),a	;store the last addition.
ld hl,NumericString_End
dec hl
disploop:
ld a,(hl)
cp 255
ret z
call &bb5a
dec hl
jr disploop
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
db 255 ;terminator when reading in reverse
NumericString:
;stored little-endian for convenience
db &39,&39,&39,&31
NumericString_End:
db 255 ;terminator
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
read "\SrcCPC\winape_stringop.asm"
Output:
2000

## zkl

In zkl, the first operand "wins" and transforms the second. So 5+"1"-->6

fcn numStringPlusOne(s){1+s}
numStringPlusOne("123") //-->124

## Zoea

program: increment_a_numerical_string
case: 1
input: '1234'
output: '1235'
case: 2
input: '19'
output: '20'`