Increment a numerical string: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎Pascal: replace and move much too complicated solution into →‎Free Pascal)
Tag: Manual revert
 
(43 intermediate revisions by 23 users not shown)
Line 8: Line 8:
=={{header|11l}}==
=={{header|11l}}==
{{trans|Python}}
{{trans|Python}}
<syntaxhighlight lang="11l">V next = String(Int(‘123’) + 1)</syntaxhighlight>

<lang 11l>V next = String(Int(‘123’) + 1)</lang>



=={{header|8080 Assembly}}==
=={{header|8080 Assembly}}==
<lang 8080asm> org 100h
<syntaxhighlight lang="8080asm"> org 100h
jmp demo
jmp demo
;;; Increment the number in the $-terminated string under HL.
;;; Increment the number in the $-terminated string under HL.
Line 67: Line 65:
pop d ; Print the string
pop d ; Print the string
mvi c,9
mvi c,9
jmp 5</lang>
jmp 5</syntaxhighlight>


=={{header|8086 Assembly}}==
=={{header|8086 Assembly}}==
<syntaxhighlight lang="asm"> cpu 8086

<lang asm> cpu 8086
bits 16
bits 16
section .text
section .text
Line 121: Line 118:
mov ah,9 ; Print the string
mov ah,9 ; Print the string
int 21h
int 21h
ret</lang>
ret</syntaxhighlight>


=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program incstring64.s */
/* program incstring64.s */
Line 194: Line 191:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
{{Output}}
{{Output}}
<pre>
<pre>
Line 207: Line 204:


=={{header|ABAP}}==
=={{header|ABAP}}==
<lang ABAP>report zz_incstring
<syntaxhighlight lang="abap">report zz_incstring
perform test using: '0', '1', '-1', '10000000', '-10000000'.
perform test using: '0', '1', '-1', '10000000', '-10000000'.


Line 218: Line 215:
write / lv_string.
write / lv_string.
endform.
endform.
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 230: Line 227:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Increment(CHAR ARRAY src,dst)
<syntaxhighlight lang="action!">PROC Increment(CHAR ARRAY src,dst)
INT val
INT val


Line 251: Line 248:
Test("-2")
Test("-2")
Test("-10000")
Test("-10000")
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Increment_a_numerical_string.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Increment_a_numerical_string.png Screenshot from Atari 8-bit computer]
Line 264: Line 261:


=={{header|ActionScript}}==
=={{header|ActionScript}}==
<lang ActionScript>function incrementString(str:String):String
<syntaxhighlight lang="actionscript">function incrementString(str:String):String
{
{
return String(Number(str)+1);
return String(Number(str)+1);
}</lang>
}</syntaxhighlight>


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


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>
<syntaxhighlight lang="aime">
o_text(itoa(atoi("2047") + 1));
o_text(itoa(atoi("2047") + 1));
o_byte('\n');
o_byte('\n');
</syntaxhighlight>
</lang>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 285: Line 282:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<lang algol68>STRING s := "12345"; FILE f; INT i;
<syntaxhighlight lang="algol68">STRING s := "12345"; FILE f; INT i;
associate(f, s); get(f,i);
associate(f, s); get(f,i);
i+:=1;
i+:=1;
s:=""; reset(f); put(f,i);
s:=""; reset(f); put(f,i);
print((s, new line))</lang>
print((s, new line))</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 297: Line 294:
=={{header|ALGOL W}}==
=={{header|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).
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).
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% returns a string representing the number in s incremented %
% returns a string representing the number in s incremented %
% As strings are fixed length, the significant length of s must %
% As strings are fixed length, the significant length of s must %
Line 373: Line 370:
write( " 123456789 + 1: " ); writeonToBlank( increment( "123456789", 9 ) );
write( " 123456789 + 1: " ); writeonToBlank( increment( "123456789", 9 ) );
write( "99999999999999999999 + 1: " ); writeonToBlank( increment( "99999999999999999999", 20 ) )
write( "99999999999999999999 + 1: " ); writeonToBlank( increment( "99999999999999999999", 20 ) )
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 383: Line 380:


=={{header|Apex}}==
=={{header|Apex}}==
<lang apex>
<syntaxhighlight lang="apex">
string count = '12345';
string count = '12345';
count = String.valueOf(integer.valueOf(count)+1);
count = String.valueOf(integer.valueOf(count)+1);
system.debug('Incremental Value : '+count);
system.debug('Incremental Value : '+count);
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>12346</pre>
<pre>12346</pre>


=={{header|APL}}==
=={{header|APL}}==
<syntaxhighlight lang="apl">⍕1+⍎'12345'</syntaxhighlight>

<lang apl>⍕1+⍎'12345'</lang>
{{Out}}
{{Out}}
<pre>12346</pre>
<pre>12346</pre>


=={{header|AppleScript}}==
=={{header|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:
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:
{{Trans|Python}}
{{Trans|Python}}
{{Trans|Haskell}}
{{Trans|Haskell}}
{{Trans|JavaScript}}
{{Trans|JavaScript}}
<lang applescript>use AppleScript version "2.4"
<syntaxhighlight lang="applescript">use AppleScript version "2.4"
use framework "Foundation"
use framework "Foundation"
use scripting additions
use scripting additions
Line 508: Line 505:
filteredArrayUsingPredicate:(ca's ¬
filteredArrayUsingPredicate:(ca's ¬
NSPredicate's predicateWithFormat:"0 < length")) as list
NSPredicate's predicateWithFormat:"0 < length")) as list
end |words|</lang>
end |words|</syntaxhighlight>
{{Out}}
{{Out}}
<pre>42 1492.3 -0.5 137
<pre>42 1492.3 -0.5 137
42 pine martens in 1492.3 -0.5 mushrooms ≠ 137</pre>
42 pine martens in 1492.3 -0.5 mushrooms ≠ 137</pre>
----
===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:

<syntaxhighlight lang="applescript">("12345" + 1) as text --> "12346"</syntaxhighlight>

The following handles more possibilities, but the number base is still resolutely decimal:

<syntaxhighlight lang="applescript">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") ¬
}</syntaxhighlight>

{{output}}
(On a machine configured for "en_GB".)
<syntaxhighlight lang="applescript">{"12346", "1,000,000,000,000,004", "8.766", "-2,34E+0", "-2.34 x 10^0"}</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 719: Line 796:
.align 4
.align 4
.Ls_magic_number_10: .word 0x66666667
.Ls_magic_number_10: .word 0x66666667


</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>num: "12349"
<syntaxhighlight lang="rebol">num: "12349"


print ["The next number is:" (to :integer num)+1]</lang>
print ["The next number is:" (to :integer num)+1]</syntaxhighlight>


{{out}}
{{out}}
Line 733: Line 809:


=={{header|Asymptote}}==
=={{header|Asymptote}}==
<lang Asymptote>string cadena = "12345.78";
<syntaxhighlight lang="asymptote">string cadena = "12345.78";
cadena = string((real)cadena + 1);
cadena = string((real)cadena + 1);
write(cadena);</lang>
write(cadena);</syntaxhighlight>
{{out}}
{{out}}
<pre>12346.78</pre>
<pre>12346.78</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>str = 12345
<syntaxhighlight lang="autohotkey">str = 12345
MsgBox % str += 1</lang>
MsgBox % str += 1</syntaxhighlight>
{{Out}}
{{Out}}
<pre>12346</pre>
<pre>12346</pre>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<lang autoIt>Global $x = "12345"
<syntaxhighlight lang="autoit">Global $x = "12345"
$x += 1
$x += 1
MsgBox(0,"",$x)</lang>
MsgBox(0,"",$x)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>12346</pre>
<pre>12346</pre>


=={{header|Avail}}==
=={{header|Avail}}==
<lang Avail>numberString ::= "1080";
<syntaxhighlight lang="avail">numberString ::= "1080";
incremented ::= numberString (base 10) + 1;</lang>
incremented ::= numberString (base 10) + 1;</syntaxhighlight>


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


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|Applesoft BASIC}}

{{works with|BaCon}}
{{works with|BaCon}}


Line 777: Line 855:
{{works with|Yabasic}}
{{works with|Yabasic}}


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

==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="gwbasic">S$ = "12345":S$ = STR$ ( VAL (S$) + 1)</syntaxhighlight>


==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang freebasic>cadena$ = "12345"
<syntaxhighlight lang="freebasic">cadena$ = "12345"
cadena$ = string(val(cadena$) + 1)
cadena$ = string(val(cadena$) + 1)
#or also
#or also
cadena$ = string(FromRadix(cadena$,10) + 1)</lang>
cadena$ = string(FromRadix(cadena$,10) + 1)</syntaxhighlight>


==={{header|OxygenBasic}}===
==={{header|OxygenBasic}}===
When a number is assigned to a string, it autoconverts.
When a number is assigned to a string, it autoconverts.
<lang>
<syntaxhighlight lang="text">
string s="122"
string s="122"
s=val(s)+1
s=val(s)+1
print s 'result: "123"
print s 'result: "123"
</syntaxhighlight>
</lang>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
{{works with|QBasic}}
{{works with|QBasic}}
<lang qbasic>LET cadena$ = "12345"
<syntaxhighlight lang="qbasic">LET cadena$ = "12345"
LET cadena$ = STR$(VAL(cadena$) + 1)
LET cadena$ = STR$(VAL(cadena$) + 1)
PRINT cadena$
PRINT cadena$
END</lang>
END</syntaxhighlight>


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang yabasic>cadena$ = "12345"
<syntaxhighlight lang="yabasic">cadena$ = "12345"
cadena$ = str$(val(cadena$) + 1)</lang>
cadena$ = str$(val(cadena$) + 1)</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 LET S$="12345"
<syntaxhighlight lang="is-basic">100 LET S$="12345"
110 LET S$=STR$(VAL(S$)+1)</lang>
110 LET S$=STR$(VAL(S$)+1)</syntaxhighlight>


==={{header|ZX Spectrum Basic}}===
==={{header|ZX Spectrum Basic}}===

The ZX Spectrum needs line numbers and a let statement,
The ZX Spectrum needs line numbers and a let statement,
but the same technique can be used:
but the same technique can be used:
<syntaxhighlight lang="zxbasic">10 LET s$ = "12345"

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


=={{header|Batch File}}==
=={{header|Batch File}}==
Line 821: Line 900:


{{works with|Windows NT|4}}
{{works with|Windows NT|4}}
<lang dos>set s=12345
<syntaxhighlight lang="dos">set s=12345
set /a s+=1</lang>
set /a s+=1</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
This assumes the task is about incrementing an ''arbitrary-length'' decimal string.
This assumes the task is about incrementing an ''arbitrary-length'' decimal string.
<lang bbcbasic> num$ = "567"
<syntaxhighlight lang="bbcbasic"> num$ = "567"
REPEAT
REPEAT
PRINT num$
PRINT num$
Line 843: Line 922:
UNTIL A$<>"0" OR I%=0
UNTIL A$<>"0" OR I%=0
IF A$="0" n$ = "1" + n$
IF A$="0" n$ = "1" + n$
ENDPROC</lang>
ENDPROC</syntaxhighlight>


=={{header|Boo}}==
=={{header|Boo}}==
<lang boo>s = "1234"
<syntaxhighlight lang="boo">s = "1234"
s = (int.Parse(s) + 1).ToString()</lang>
s = (int.Parse(s) + 1).ToString()</syntaxhighlight>


=={{header|BQN}}==
=={{header|BQN}}==
<lang BQN>1•Repr∘+•BQN "1234"</lang>
<syntaxhighlight lang="bqn">1•Repr∘+•BQN "1234"</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
Numbers are strings. Bracmat supports rational numbers, including integers, using arbitrary-precision arithmetic. Pure imaginary numbers are formed using a factor <code>i</code> (or <code>-i</code>). There is no support for floating point arithmetics. (Historically, because the ARM 2 processor in the Archimedes computer didn't sport an FPU.)
Numbers are strings. Bracmat supports rational numbers, including integers, using arbitrary-precision arithmetic. Pure imaginary numbers are formed using a factor <code>i</code> (or <code>-i</code>).
<lang bracmat>(n=35664871829866234762187538073934873121878/6172839450617283945)
<syntaxhighlight lang="bracmat">(n=35664871829866234762187538073934873121878/6172839450617283945)
&!n+1:?n
&!n+1:?n
&out$!n
&out$!n


35664871829866234762193710913385490405823/6172839450617283945
35664871829866234762193710913385490405823/6172839450617283945
</syntaxhighlight>
</lang>
Output
<pre></pre>

Bracmat also supports floating point numbers, but only in a sandboxed way. To increment 0.234E0 by 1:

<syntaxhighlight lang="bracmat">(new$(UFP,(=(s.val).!val+1)).go)$"0.234e0"</syntaxhighlight>
Output
<pre>1.2340000000000000E+00</pre>

<code>UFP</code> is a new (2023) object type that specializes in compiling and executing floating point operations. Bracmat code must be passed when a UFP object is created. This code has a more restricted grammar than Bracmat code in general. The passed code must be the definition of a function that can take one or more scalars or arrays as argument. In the example, this function is <code>(=(s.val).!val+1)</code>. The expression <code>(s.val)</code> says that the function takes a scalar and binds it to the local variable <code>val</code>. In the example, the function is defined, compiled, executed and destroyed in one go. This is not necessary; it is perfectly possible to use the compiled UFP object multiple times before destroying it.


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>#Convert to integer, increment, then back to string
<syntaxhighlight lang="brat">#Convert to integer, increment, then back to string
p ("100".to_i + 1).to_s #Prints 101</lang>
p ("100".to_i + 1).to_s #Prints 101</syntaxhighlight>


=={{header|Burlesque}}==
=={{header|Burlesque}}==
<syntaxhighlight lang="burlesque">

<lang burlesque>
ri?ish
ri?ish
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
Handling strings of arbitrary sizes:<lang c>#include <stdio.h>
Handling strings of arbitrary sizes:<syntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <string.h>
#include <stdlib.h>
#include <stdlib.h>
Line 941: Line 1,029:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{Out}}<pre>
{{Out}}<pre>
text: +0
text: +0
Line 961: Line 1,049:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>string s = "12345";
<syntaxhighlight lang="csharp">string s = "12345";
s = (int.Parse(s) + 1).ToString();
s = (int.Parse(s) + 1).ToString();
// The above functions properly for strings >= Int32.MinValue and
// The above functions properly for strings >= Int32.MinValue and
Line 973: Line 1,061:
bis = (BigInteger.Parse(bis) + 1).ToString();
bis = (BigInteger.Parse(bis) + 1).ToString();
// Note that extremely long strings will take a long time to parse
// Note that extremely long strings will take a long time to parse
// and convert from a BigInteger back into a string.</lang>
// and convert from a BigInteger back into a string.</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>// standard C++ string stream operators
<syntaxhighlight lang="cpp">// standard C++ string stream operators
#include <cstdlib>
#include <cstdlib>
#include <string>
#include <string>
Line 991: Line 1,079:


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


{{works with|C++11}}
{{works with|C++11}}
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>


std::string s = "12345";
std::string s = "12345";
s = std::to_string(1+std::stoi(s));</lang>
s = std::to_string(1+std::stoi(s));</syntaxhighlight>


{{libheader|Boost}}
{{libheader|Boost}}
<lang cpp>// Boost
<syntaxhighlight lang="cpp">// Boost
#include <cstdlib>
#include <cstdlib>
#include <string>
#include <string>
Line 1,008: Line 1,096:
std::string s = "12345";
std::string s = "12345";
int i = boost::lexical_cast<int>(s) + 1;
int i = boost::lexical_cast<int>(s) + 1;
s = boost::lexical_cast<std::string>(i);</lang>
s = boost::lexical_cast<std::string>(i);</syntaxhighlight>


{{libheader|Qt}}
{{libheader|Qt}}
{{uses from|Library|Qt|component1=QString}}
{{uses from|Library|Qt|component1=QString}}
<lang cpp>// Qt
<syntaxhighlight lang="cpp">// Qt
QString num1 = "12345";
QString num1 = "12345";
QString num2 = QString("%1").arg(v1.toInt()+1);</lang>
QString num2 = QString("%1").arg(v1.toInt()+1);</syntaxhighlight>


{{Libheader|MFC}}
{{Libheader|MFC}}
Line 1,020: Line 1,108:
{{uses from|Library|C Runtime|component1=_ttoi|component2=_tcstoul}} <!-- They're Microsoft-specific extensions exported in tchar.h. That'll be noted on their relevant pages.-->
{{uses from|Library|C Runtime|component1=_ttoi|component2=_tcstoul}} <!-- They're Microsoft-specific extensions exported in tchar.h. That'll be noted on their relevant pages.-->


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


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


{{works with|g++|4.0.2}}
{{works with|g++|4.0.2}}
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <iostream>
#include <iostream>
#include <ostream>
#include <ostream>
Line 1,054: Line 1,142:
increment_numerical_string(big_number);
increment_numerical_string(big_number);
std::cout << "after increment: " << big_number << "\n";
std::cout << "after increment: " << big_number << "\n";
}</lang>
}</syntaxhighlight>


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>shared void run() {
<syntaxhighlight lang="ceylon">shared void run() {
"Increments a numeric string by 1. Returns a float or integer depending on the string.
"Increments a numeric string by 1. Returns a float or integer depending on the string.
Line 1,074: Line 1,162:
value d = inc(c);
value d = inc(c);
print(d);
print(d);
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(str (inc (Integer/parseInt "1234")))</lang>
<syntaxhighlight lang="lisp">(str (inc (Integer/parseInt "1234")))</syntaxhighlight>


=={{header|CMake}}==
=={{header|CMake}}==
CMake performs all arithmetic with numeric strings, through its math() command.
CMake performs all arithmetic with numeric strings, through its math() command.


<lang cmake>set(string "1599")
<syntaxhighlight lang="cmake">set(string "1599")
math(EXPR string "${string} + 1")
math(EXPR string "${string} + 1")
message(STATUS "${string}")</lang>
message(STATUS "${string}")</syntaxhighlight>


<pre>-- 1600</pre>
<pre>-- 1600</pre>


=={{header|COBOL}}==
=={{header|COBOL}}==
<lang cobol> PROGRAM-ID. increment-num-str.
<syntaxhighlight lang="cobol"> PROGRAM-ID. increment-num-str.
DATA DIVISION.
DATA DIVISION.
Line 1,102: Line 1,190:


GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


The following example also increments a numerical string, although it does not apear to. num-str is implicitly defined as <code>USAGE DISPLAY</code> which means its contents will be stored as characters. This means num-str is effectively a string of (numeric) characters.
The following example also increments a numerical string, although it does not apear to. num-str is implicitly defined as <code>USAGE DISPLAY</code> which means its contents will be stored as characters. This means num-str is effectively a string of (numeric) characters.
<lang cobol> PROGRAM-ID. increment-num-str.
<syntaxhighlight lang="cobol"> PROGRAM-ID. increment-num-str.
DATA DIVISION.
DATA DIVISION.
Line 1,117: Line 1,205:
GOBACK
GOBACK
.</lang>
.</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(princ-to-string (1+ (parse-integer "1234")))</lang>
<syntaxhighlight lang="lisp">(princ-to-string (1+ (parse-integer "1234")))</syntaxhighlight>


=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
BlackBox Component Builder
BlackBox Component Builder
<lang oberon2>
<syntaxhighlight lang="oberon2">
MODULE Operations;
MODULE Operations;
IMPORT StdLog,Args,Strings;
IMPORT StdLog,Args,Strings;
Line 1,149: Line 1,237:


END Operations.
END Operations.
</syntaxhighlight>
</lang>
Execute: ^Q Operatiosn.DoIncString 124343~<br/>
Execute: ^Q Operatiosn.DoIncString 124343~<br/>
{{Out}}
{{Out}}
Line 1,157: Line 1,245:


=={{header|D}}==
=={{header|D}}==
<lang d>void main() {
<syntaxhighlight lang="d">void main() {
import std.string;
import std.string;


immutable s = "12349".succ;
immutable s = "12349".succ;
assert(s == "12350");
assert(s == "12350");
}</lang>
}</syntaxhighlight>

=={{header|dc}}==
<syntaxhighlight lang="dc">? 1 + p</syntaxhighlight>
The program expects a string on ''stdin'':
<syntaxhighlight lang="sh">echo '12345678899' | dc inc.dc</syntaxhighlight>
{{out}}
<pre>12345678900</pre>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang Delphi>program IncrementNumericalString;
<syntaxhighlight lang="delphi">program IncrementNumericalString;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 1,177: Line 1,272:


Readln;
Readln;
end.</lang>
end.</syntaxhighlight>


{{Out}}
{{Out}}
<pre>"12345" + 1 = 123456</pre>
<pre>"12345" + 1 = 123456</pre>

=={{header|dt}}==
<syntaxhighlight lang="dt">"1234567889" to-int 1 + to-string</syntaxhighlight>


=={{header|Dyalect}}==
=={{header|Dyalect}}==
<lang dyalect>var str = "42"
<syntaxhighlight lang="dyalect">var str = "42"
str = (parse(str) + 1).ToString()
str = (parse(str) + 1).ToString()


Line 1,192: Line 1,290:
str = "\(parse(str) + 1)"
str = "\(parse(str) + 1)"


print(str) //Outputs 45</lang>
print(str) //Outputs 45</syntaxhighlight>


=={{header|DWScript}}==
=={{header|DWScript}}==
<lang Delphi>var value : String = "1234";
<syntaxhighlight lang="delphi">var value : String = "1234";
value := IntToStr(StrToInt(value) + 1);
value := IntToStr(StrToInt(value) + 1);
PrintLn(value);</lang>
PrintLn(value);</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu> !. to-str ++ to-num "100"</lang>
<syntaxhighlight lang="dejavu"> !. to-str ++ to-num "100"</syntaxhighlight>


{{out}}
{{out}}
Line 1,206: Line 1,304:


=={{header|E}}==
=={{header|E}}==
<lang e>__makeInt("1234", 10).next().toString(10)</lang>
<syntaxhighlight lang="e">__makeInt("1234", 10).next().toString(10)</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==


<lang>a$ = "12"
<syntaxhighlight lang="text">a$ = "12"
a$ = number a$ + 1
a$ = number a$ + 1
print a$</lang>
print a$</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(number->string (1+ (string->number "665")))
(number->string (1+ (string->number "665")))
→ "666"
→ "666"
</syntaxhighlight>
</lang>

=={{header|Ecstasy}}==
Ecstasy provides two types that represent various numbers as if they were String values: IntLiteral and FPLiteral. For example:
<syntaxhighlight lang="java">String s = "12345";
IntLiteral lit1 = new IntLiteral(s);
IntLiteral lit2 = 6789;
++lit1; // lit1=12346
++lit2; // lit2=6790</syntaxhighlight>


=={{header|Eero}}==
=={{header|Eero}}==
<lang objc>#import <Foundation/Foundation.h>
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>


int main()
int main()
Line 1,229: Line 1,335:


Log( '%@', s )
Log( '%@', s )
return 0</lang>
return 0</syntaxhighlight>


=={{header|EGL}}==
=={{header|EGL}}==
<lang EGL>s string = "12345";
<syntaxhighlight lang="egl">s string = "12345";
s = 1 + s; // Note: s + 1 is a string concatenation.</lang>
s = 1 + s; // Note: s + 1 is a string concatenation.</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
APPLICATION
APPLICATION
Line 1,259: Line 1,365:


end
end
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,269: Line 1,375:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x:
ELENA 4.x:
<lang elena>import extensions;
<syntaxhighlight lang="elena">import extensions;
public program()
public program()
Line 1,277: Line 1,383:
console.printLine(s)
console.printLine(s)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,285: Line 1,391:
=={{header|Elixir}}==
=={{header|Elixir}}==
Values can be converted to integers then converted back after incrementing
Values can be converted to integers then converted back after incrementing
<lang Elixir>increment1 = fn n -> to_string(String.to_integer(n) + 1) end
<syntaxhighlight lang="elixir">increment1 = fn n -> to_string(String.to_integer(n) + 1) end
# Or piped
# Or piped
increment2 = fn n -> n |> String.to_integer |> +1 |> to_string end
increment2 = fn n -> n |> String.to_integer |> +1 |> to_string end


increment1.("1")
increment1.("1")
increment2.("100")</lang>
increment2.("100")</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,299: Line 1,405:


'''Case of char list:'''
'''Case of char list:'''
<lang Elixir>iex(1)> (List.to_integer('12345') + 1) |> to_char_list
<syntaxhighlight lang="elixir">iex(1)> (List.to_integer('12345') + 1) |> to_char_list
'12346'</lang>
'12346'</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(1+ (string-to-number "12345"))</syntaxhighlight>


=={{header|EMal}}==
<lang lisp>(1+ (string-to-number "12345"))</lang>
<syntaxhighlight lang="emal">
fun incrementGeneric = text by generic T, text numerical
return text!(:T!numerical + 1)
end
fun increment = text by text numerical
return incrementGeneric(when(numerical.contains("."), real, int), numerical)
end
writeLine(incrementGeneric(real, "123.32"))
writeLine(incrementGeneric(int, "123"))
writeLine(increment("123.32"))
writeLine(increment("123"))
</syntaxhighlight>
{{out}}
<pre>
124.32
124
124.32
124
</pre>


=={{header|Erlang}}==
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">integer_to_list(list_to_integer("1336")+1).</syntaxhighlight>

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


=={{header|ERRE}}==
=={{header|ERRE}}==
<lang>
<syntaxhighlight lang="text">
....................
....................
s$="12345"
s$="12345"
s$=STR$(VAL(s$)+1)
s$=STR$(VAL(s$)+1)
....................
....................
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>include get.e
<syntaxhighlight lang="euphoria">include get.e


function val(sequence s)
function val(sequence s)
Line 1,330: Line 1,455:


s = "12345"
s = "12345"
s = sprintf("%d",{val(s)+1})</lang>
s = sprintf("%d",{val(s)+1})</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
<lang fsharp>let next = string( int( "1234" ) + 1 )</lang>
// Increment a numerical string. Nigel Galloway: April 4th., 2023
let inc=int>>(+)1>>string
printfn "%s" (inc("1234"))
</syntaxhighlight>
{{out}}
<pre>
1235
</pre>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>"1234" string>number 1 + number>string</lang>
<syntaxhighlight lang="factor">"1234" string>number 1 + number>string</syntaxhighlight>


=={{header|Fantom}}==
=={{header|Fantom}}==

Within 'fansh':
Within 'fansh':


<lang fantom>
<syntaxhighlight lang="fantom">
fansh> a := "123"
fansh> a := "123"
123
123
fansh> (a.toInt + 1).toStr
fansh> (a.toInt + 1).toStr
124
124
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
Line 1,354: Line 1,486:
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.
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 )
<syntaxhighlight lang="forth">: >string ( d -- addr n )
dup >r dabs <# #s r> sign #> ;
dup >r dabs <# #s r> sign #> ;


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


Here is a version that can increment by any value
Here is a version that can increment by any value


<lang forth>: inc-string ( addr n -- )
<syntaxhighlight lang="forth">: inc-string ( addr n -- )
over count number? not abort" invalid number"
over count number? not abort" invalid number"
rot s>d d+ >string rot place ;</lang>
rot s>d d+ >string rot place ;</syntaxhighlight>


Test the first version like this:
Test the first version like this:


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


And the second one like this:
And the second one like this:


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


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
Using 'internal' files you can increment both integer and real strings
Using 'internal' files you can increment both integer and real strings
<lang fortran>CHARACTER(10) :: intstr = "12345", realstr = "1234.5"
<syntaxhighlight lang="fortran">CHARACTER(10) :: intstr = "12345", realstr = "1234.5"
INTEGER :: i
INTEGER :: i
REAL :: r
REAL :: r
Line 1,392: Line 1,524:
READ(realstr, "(F10.1)") r
READ(realstr, "(F10.1)") r
r = r + 1.0
r = r + 1.0
WRITE(realstr, "(F10.1)") r</lang>
WRITE(realstr, "(F10.1)") r</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Function Increment (num As String) As String
Function Increment (num As String) As String
Line 1,409: Line 1,541:
Print
Print
Print "Press any key to exit"
Print "Press any key to exit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,421: Line 1,553:
</pre>
</pre>


=={{header|Free Pascal}}==
=={{header|Frink}}==
The following works for integers, rational numbers, complex numbers, floating-point, etc.
not like [[#Delphi|Delphi]] doing two conversion, but increment a string by 1 is much faster.
<syntaxhighlight lang="frink">a = input["Enter number: "]
Here with different bases upto 10.After this there must be a correction to convert values > '9' to 'A'...
toString[eval[a] + 1]</syntaxhighlight>
Only for positive integer strings as high speed counter.
<lang pascal>program StrInc;
//increments a positive numerical string in different bases.
//the string must be preset with a value, length >0 ;
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
{$IFDEF FPC}
{$Mode Delphi} {$Optimization ON,ALL}{$Align 32}
uses
sysutils;
{$ELSE}
uses
system.SysUtils;
{$ENDIF}
type
myString = AnsiString; // string[32];//
function IncLoop(ps: pChar;le,Base: NativeInt):NativeInt;inline;
//Add 1 and correct carry
//returns 0, if no overflow, else -1
var
dg: nativeInt;
Begin
dec(le);//ps is 0-based
repeat
dg := ord(ps[le])+(-ord('0')+1);
result := -ord(dg>=base);// -1 or 0 -> $FF...FF or $00...00
ps[le] := chr(-(result AND base)+dg+ord('0'));
dec(le);
until (result = 0) or (le<0);
end;


=={{header|FTCBASIC}}==
procedure IncIntStr(base:NativeInt;var s:myString);
<syntaxhighlight lang="basic">define value = 0, text$ = "12345"
begin
//overflow -> prepend a '1' to string
if (IncLoop(pChar(@s[1]),length(s),base) <>0) then
s := '1'+s;
end;


strint value,text$
const
+1 value
ONE_BILLION = 1000*1000*1000;
intstr text$,value
strLen = 26;
MAX = 1 shl strLen -1;
var
s : myString;
i,base : nativeInt;
T0: TDateTime;
Begin
writeln(MAX,' increments in base');
For base := 2 to 10 do
Begin
//s := '0' doesn't work
setlength(s,1);
s[1]:= '0';
{ //Zero pad string
setlength(s,strLen);fillchar(s[1],strLen,'0');
}
T0 := time;
For i := 1 to MAX do
IncIntStr(Base,s);
T0 := (time-T0)*86400;
writeln(s:strLen,' base ',base:2,T0:8:3,' s');
end;
writeln;
writeln('One billion digits "9"');
setlength(s,ONE_BILLION+1);
s[1]:= '0';//don't measure setlength in IncIntStr
fillchar(s[2],length(s)-1,'9');
writeln('first 5 digits ',s[1],s[2],s[3],s[4],s[5]);
T0 := time;
IncIntStr(10,s);
T0 := (time-T0)*86400;
writeln(length(s):10,T0:8:3,' s');
writeln('first 5 digits ',s[1],s[2],s[3],s[4],s[5]);
s:='';
{$IFDEF WINDOWS}
readln;
{$ENDIF}
end.
</lang>
{{out|@TIO.RUN}}
<pre>
67108863 increments in base
11111111111111111111111111 base 2 0.451 s
11200021111001110 base 3 0.394 s
3333333333333 base 4 0.339 s
114134440423 base 5 0.363 s
10354213103 base 6 0.358 s
1443262443 base 7 0.320 s
377777777 base 8 0.310 s
150244043 base 9 0.308 s
67108863 base 10 0.301 s // without inline 0.364


print text$
One billion digits "9"
pause
first 5 digits 09999
end</syntaxhighlight>
1000000001 1.813 s
first 5 digits 10000
</pre>

=={{header|Frink}}==
The following works for integers, rational numbers, complex numbers, floating-point, etc.
<lang frink>
a = input["Enter number: "]
toString[eval[a] + 1]
</lang>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang futurebasic>
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
include "NSLog.incl"


Line 1,544: Line 1,580:
next
next
HandleEvents
HandleEvents
</syntaxhighlight>
</lang>


Output:
Output:
Line 1,562: Line 1,598:
=={{header|Fōrmulæ}}==
=={{header|Fōrmulæ}}==


{{FormulaeEntry|page=https://formulae.org/?script=examples/Increment_a_numerical_string}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.

'''Solution'''


[[File:Fōrmulæ - Increment a numerical string 01.png]]
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.


[[File:Fōrmulæ - Increment a numerical string 02.png]]
In '''[https://formulae.org/?example=Increment_a_numerical_string this]''' page you can see the program(s) related to this task and their results.


=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=e31b63f444c2c09c8b1436407020e216 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=e31b63f444c2c09c8b1436407020e216 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()
Dim vInput As Variant = "12345"
Dim vInput As Variant = "12345"


Line 1,576: Line 1,614:
Print vInput
Print vInput


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,583: Line 1,621:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap># Using built-in functions
<syntaxhighlight lang="gap"># Using built-in functions
Incr := s -> String(Int(s) + 1);
Incr := s -> String(Int(s) + 1);


Line 1,612: Line 1,650:
Increment(s);
Increment(s);
s;
s;
# "2400"</lang>
# "2400"</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
Concise:
Concise:
<lang go>package main
<syntaxhighlight lang="go">package main
import "fmt"
import "fmt"
import "strconv"
import "strconv"
Line 1,622: Line 1,660:
i, _ := strconv.Atoi("1234")
i, _ := strconv.Atoi("1234")
fmt.Println(strconv.Itoa(i + 1))
fmt.Println(strconv.Itoa(i + 1))
}</lang>
}</syntaxhighlight>
More:
More:
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 1,701: Line 1,739:
bs = b.Add(&b, &one).String()
bs = b.Add(&b, &one).String()
fmt.Println("incremented:", bs)
fmt.Println("incremented:", bs)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,724: Line 1,762:


=={{header|Golfscript}}==
=={{header|Golfscript}}==
<lang golfscript>~)`</lang>
<syntaxhighlight lang="golfscript">~)`</syntaxhighlight>
With a test framework to supply a number:
With a test framework to supply a number:
<lang golfscript>"1234" ~)` p</lang>
<syntaxhighlight lang="golfscript">"1234" ~)` p</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>println ((("23455" as BigDecimal) + 1) as String)
<syntaxhighlight lang="groovy">println ((("23455" as BigDecimal) + 1) as String)
println ((("23455.78" as BigDecimal) + 1) as String)</lang>
println ((("23455.78" as BigDecimal) + 1) as String)</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,738: Line 1,776:


=={{header|Haskell}}==
=={{header|Haskell}}==
<!--<lang haskell>((show :: Integer -> String) . succ . read) "1234"</lang>
<!--<syntaxhighlight lang="haskell">((show :: Integer -> String) . succ . read) "1234"</syntaxhighlight>


At least one type signature somewhere in the code is necessary, because otherwise there is no specification of what kind of value should be incremented; the operation is equally applicable to any instance of <tt>Enum</tt>:
At least one type signature somewhere in the code is necessary, because otherwise there is no specification of what kind of value should be incremented; the operation is equally applicable to any instance of <tt>Enum</tt>:


<lang haskell>((show :: Bool -> String) . succ . read) "False"</lang>-->
<syntaxhighlight lang="haskell">((show :: Bool -> String) . succ . read) "False"</syntaxhighlight>-->


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


or, for Integral values, we can use the Prelude's '''succ''' function:
or, for Integral values, we can use the Prelude's '''succ''' function:


<lang haskell>(show . succ) (read "1234" :: Int)</lang>
<syntaxhighlight lang="haskell">(show . succ) (read "1234" :: Int)</syntaxhighlight>


and to extend the range of a succString function to allow for both floating point and integral numeric strings, for non-numeric noise, for multiple numeric expressions within a single string, and for an option to retain or prune any non-numeric noise, we could write things like:
and to extend the range of a succString function to allow for both floating point and integral numeric strings, for non-numeric noise, for multiple numeric expressions within a single string, and for an option to retain or prune any non-numeric noise, we could write things like:


{{Trans|Python}}
{{Trans|Python}}
<lang haskell>import Text.Read (readMaybe)
<syntaxhighlight lang="haskell">import Text.Read (readMaybe)
import Data.Maybe (mapMaybe)
import Data.Maybe (mapMaybe)


Line 1,782: Line 1,820:
(putStrLn . unlines) $
(putStrLn . unlines) $
succString <$> [True, False] <*>
succString <$> [True, False] <*>
pure "41.0 pine martens in 1491 -1.5 mushrooms ≠ 136"</lang>
pure "41.0 pine martens in 1491 -1.5 mushrooms ≠ 136"</syntaxhighlight>
{{Out}}
{{Out}}
<pre>42.0 1492 -0.5 137
<pre>42.0 1492 -0.5 137
Line 1,788: Line 1,826:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang hicest>CHARACTER string = "123 -4567.89"
<syntaxhighlight lang="hicest">CHARACTER string = "123 -4567.89"


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


=={{header|HolyC}}==
=={{header|HolyC}}==
<lang holyc>I8 *s;
<syntaxhighlight lang="holyc">I8 *s;


s = "10";
s = "10";
Line 1,802: Line 1,840:
s = "-10";
s = "-10";
s = Str2I64(s) + 1;
s = Str2I64(s) + 1;
Print("%d\n", s);</lang>
Print("%d\n", s);</syntaxhighlight>


=={{header|Hy}}==
=={{header|Hy}}==
<lang clojure>(str (inc (int "123")))</lang>
<syntaxhighlight lang="clojure">(str (inc (int "123")))</syntaxhighlight>
Alternatively, with the "threading" macro:
Alternatively, with the "threading" macro:
<lang clojure>(-> "123" (int) (inc) (str))</lang>
<syntaxhighlight lang="clojure">(-> "123" (int) (inc) (str))</syntaxhighlight>


=={{header|HyperTalk}}==
=={{header|HyperTalk}}==
<lang hypertalk>put 0 into someVar
<syntaxhighlight lang="hypertalk">put 0 into someVar
add 1 to someVar
add 1 to someVar
-- without "into [field reference]" the value will appear
-- without "into [field reference]" the value will appear
-- in the message box
-- in the message box
put someVar -- into cd fld 1</lang>
put someVar -- into cd fld 1</syntaxhighlight>


=={{header|i}}==
=={{header|i}}==
<lang i>software {
<syntaxhighlight lang="i">software {
string = "1"
string = "1"
string += 1
string += 1
print(string)
print(string)
}</lang>
}</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|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.
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
<syntaxhighlight lang="icon">s := "123" # s is a string
s +:= 1 # s is now an integer</lang>
s +:= 1 # s is now an integer</syntaxhighlight>


=={{header|IDL}}==
=={{header|IDL}}==
<lang idl>str = '1234'
<syntaxhighlight lang="idl">str = '1234'
print, string(fix(str)+1)
print, string(fix(str)+1)
;==> 1235</lang>
;==> 1235</syntaxhighlight>


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


<lang idl>print, '1234' + 1
<syntaxhighlight lang="idl">print, '1234' + 1
;==> 1235</lang>
;==> 1235</syntaxhighlight>


=={{header|Inform 7}}==
=={{header|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]]).
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.
<syntaxhighlight lang="inform7">Home is a room.


To decide which indexed text is incremented (T - indexed text):
To decide which indexed text is incremented (T - indexed text):
Line 1,855: Line 1,893:
When play begins:
When play begins:
say incremented "12345";
say incremented "12345";
end the story.</lang>
end the story.</syntaxhighlight>


=={{header|Io}}==
=={{header|Io}}==
<lang>str := ("123" asNumber + 1) asString</lang>
<syntaxhighlight lang="text">str := ("123" asNumber + 1) asString</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang j>incrTextNum=: >:&.".</lang>
<syntaxhighlight lang="j">incrTextNum=: >:&.".</syntaxhighlight>


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.
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 (though mixing these notations will coerce all values in the list to a lowest common denominator type).
<lang j> incrTextNum '34.5'
<syntaxhighlight lang="j"> incrTextNum '34.5'
35.5
35.5
incrTextNum '7 0.2 3r5 2j4 5.7e_4'
incrTextNum '7 0.2 3r5 2j4 5.7e_4'
8 1.2 1.6 3j4 1.00057</lang>
8 1.2 1.6 3j4 1.00057</syntaxhighlight>


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:
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'
<syntaxhighlight lang="j"> |.incrTextNum'123 456'
754 421
754 421
|.1+123 456
|.1+123 456
457 124</lang>
457 124</syntaxhighlight>


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


Another solution that works with big decimal numbers:
Another solution that works with big decimal numbers:
<lang java>String s = "123456789012345678901234567890.12345";
<syntaxhighlight lang="java">String s = "123456789012345678901234567890.12345";
s = new BigDecimal(s).add(BigDecimal.ONE).toString();</lang>
s = new BigDecimal(s).add(BigDecimal.ONE).toString();</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 1,890: Line 1,928:
Using implicit coercion:
Using implicit coercion:


<lang javascript>let s = '9999';
<syntaxhighlight lang="javascript">let s = '9999';
let splusplus = (+s+1)+""
let splusplus = (+s+1)+""


console.log([splusplus, typeof splusplus]) // 10000,string</lang>
console.log([splusplus, typeof splusplus]) // 10000,string</syntaxhighlight>


Or, expanding the range of a '''stringSucc''' function to allow for non-numeric noise, and also for multiple numeric expressions in a single string:
Or, expanding the range of a '''stringSucc''' function to allow for non-numeric noise, and also for multiple numeric expressions in a single string:
Line 1,899: Line 1,937:
{{Trans|Python}}
{{Trans|Python}}
{{Trans|Haskell}}
{{Trans|Haskell}}
<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 1,957: Line 1,995:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
<pre>42 1492.3 -0.5 137
<pre>42 1492.3 -0.5 137
42 pine martens in 1492.3 -0.5 mushrooms ≠ 137</pre>
42 pine martens in 1492.3 -0.5 mushrooms ≠ 137</pre>

=={{header|Joy}}==
<syntaxhighlight lang="jq">DEFINE incstr == 10 strtol succ 'd 1 1 format.

"1234567889" incstr.</syntaxhighlight>
{{out}}
<pre>"1234567890"</pre>


=={{header|jq}}==
=={{header|jq}}==
====tonumber====
====tonumber====
jq's string-to-number filter is called <tt>tonumber</tt>. For example, if we have a file named input.txt consisting of string representations of numbers, one per line, we could compute the sum as follows:
jq's string-to-number filter is called <tt>tonumber</tt>. For example, if we have a file named input.txt consisting of string representations of numbers, one per line, we could compute the sum as follows:
<lang sh>$ jq -n -M -s 'map(tonumber) | add' input.txt</lang>
<syntaxhighlight lang="sh">$ jq -n -M -s 'map(tonumber) | add' input.txt</syntaxhighlight>


More precisely, <tt>tonumber</tt> will convert string representations of JSON numbers (integers and decimals) to numbers, but very large integers will be converted to decimals with possible loss of precision, and similar problems will be noticeable for very small and very large decimals.
More precisely, <tt>tonumber</tt> will convert string representations of JSON numbers (integers and decimals) to numbers, but jq version 1.6 and earlier will convert very large integers to decimals with possible loss of precision; similar problems will be noticeable for very small and very large decimals. Since the release of jq version 1.6, however, the precision of literal numbers is preserved.


The Go implementation of jq, gojq, supports unbounded-precision integer arithmetic, so for example:
<pre>
$ gojq -n '"9" * 100 | tonumber + 1'
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
</pre>
<tt>tostring</tt> can be used to convert numbers to strings.
<tt>tostring</tt> can be used to convert numbers to strings.

====long_add====
====long_add====
<lang jq># This function assumes its string arguments represent non-negative decimal integers.
<syntaxhighlight lang="jq"># This function assumes its string arguments represent non-negative decimal integers.
def long_add(num1; num2):
def long_add(num1; num2):
if (num1|length) < (num2|length) then long_add(num2; num1)
if (num1|length) < (num2|length) then long_add(num2; num1)
Line 1,989: Line 2,040:
end )
end )
| reverse | map(.+48) | implode
| reverse | map(.+48) | implode
end ;</lang>
end ;</syntaxhighlight>
'''Example'''
'''Example'''
<syntaxhighlight lang="jq">
<lang jq>
long_add("9" * 100; "1")</lang>
long_add("9" * 100; "1")</syntaxhighlight>
{{Out}}
{{Out}}
"10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
"10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>var a = "1"
<syntaxhighlight lang="javascript">var a = "1"
a = String(Number(a) + 1)</lang>
a = String(Number(a) + 1)</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>import Base.+
<syntaxhighlight lang="julia">import Base.+
Base.:+(s::AbstractString, n::Real) = string((x = tryparse(Int, s)) isa Int ? x + 1 : parse(Float64, s) + 1)
Base.:+(s::AbstractString, n::Real) = string((x = tryparse(Int, s)) isa Int ? x + 1 : parse(Float64, s) + 1)
@show "125" + 1
@show "125" + 1
@show "125.15" + 1
@show "125.15" + 1
@show "1234567890987654321" + 1
@show "1234567890987654321" + 1
</lang>{{out}}
</syntaxhighlight>{{out}}
<pre>"125" + 1 = "126"
<pre>"125" + 1 = "126"
"125.15" + 1 = "126.15"
"125.15" + 1 = "126.15"
Line 2,015: Line 2,066:
"." is a built-in function that evaluates a valid K expression.
"." is a built-in function that evaluates a valid K expression.


<lang K> 1 + ."1234"
<syntaxhighlight lang="k"> 1 + ."1234"
1235
1235
1 + ."1234.56"
1 + ."1234.56"
Line 2,023: Line 2,074:
inc:{1 + . x}
inc:{1 + . x}
inc "1234"
inc "1234"
1235</lang>
1235</syntaxhighlight>


Some other examples.
Some other examples.
<lang K> 1 + .:' ("1";"2";"3";"4")
<syntaxhighlight lang="k"> 1 + .:' ("1";"2";"3";"4")
2 3 4 5
2 3 4 5


Line 2,033: Line 2,084:


. "1","+","-10"
. "1","+","-10"
-9</lang>
-9</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.5-2
<syntaxhighlight lang="scala">// version 1.0.5-2


/** overload ++ operator to increment a numeric string */
/** overload ++ operator to increment a numeric string */
Line 2,053: Line 2,104:
ns = "ghijk" // not numeric, so won't be changed by increment operator
ns = "ghijk" // not numeric, so won't be changed by increment operator
println(++ns)
println(++ns)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,061: Line 2,112:
</pre>
</pre>


=={{header|Lambdatalk}}==
=={{header|LabVIEW}}==
{{VI snippet}}<br/>
[[File:LabVIEW_Increment_a_numerical_string.png]]


=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
In lambdatalk every expression is a word or an S-expression, so:
In lambdatalk every expression is a word or an S-expression, so:


Line 2,074: Line 2,128:
{+ 123 1} // means "add the words 123 and 1"
{+ 123 1} // means "add the words 123 and 1"
-> 124 // can do the job and returns the result as a word
-> 124 // can do the job and returns the result as a word
</syntaxhighlight>
</lang>


=={{header|LabVIEW}}==
=={{header|Lang}}==
<syntaxhighlight lang="lang">
{{VI snippet}}<br/>
$next $= text(+|int({{{123}}}))
[[File:LabVIEW_Increment_a_numerical_string.png]]
</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>(integer('123') + 1) -> asstring</lang>
<syntaxhighlight lang="lasso">(integer('123') + 1) -> asstring</syntaxhighlight>
-> 124
-> 124


=={{header|LaTeX}}==
=={{header|LaTeX}}==
<lang LaTeX>\documentclass{minimal}
<syntaxhighlight lang="latex">\documentclass{minimal}
\newcounter{tmpnum}
\newcounter{tmpnum}
\newcommand{\stringinc}[1]{%
\newcommand{\stringinc}[1]{%
Line 2,094: Line 2,149:
\begin{document}
\begin{document}
The number 12345 is followed by \stringinc{12345}.
The number 12345 is followed by \stringinc{12345}.
\end{document}</lang>
\end{document}</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>' [RC] Increment a numerical string.
<syntaxhighlight lang="lb">' [RC] Increment a numerical string.


o$ ="12345"
o$ ="12345"
Line 2,106: Line 2,161:
print o$
print o$


end</lang>
end</syntaxhighlight>


=={{header|LIL}}==
=={{header|LIL}}==
<lang tcl>##
<syntaxhighlight lang="tcl">##
Increment a numerical string, in LIL
Increment a numerical string, in LIL
##
##
set a "41"
set a "41"
inc a
inc a
print $a</lang>
print $a</syntaxhighlight>


{{out}}
{{out}}
Line 2,121: Line 2,176:


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>put integer("123")+1
<syntaxhighlight lang="lingo">put integer("123")+1
-- 124</lang>
-- 124</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
LiveCode casts types transparently. When storing a number in a variable, the internal representation is numeric (a double, I think), and if the variable is used as a number, there is no type conversion.
LiveCode casts types transparently. When storing a number in a variable, the internal representation is numeric (a double, I think), and if the variable is used as a number, there is no type conversion.
If the variable is used as a string, the conversion is automatic; likewise if a string variable containing a number is used as a number:
If the variable is used as a string, the conversion is automatic; likewise if a string variable containing a number is used as a number:
<lang LiveCode>put "0" & "1234" into myString -- I think this will result in an internal string representation
<syntaxhighlight lang="livecode">put "0" & "1234" into myString -- I think this will result in an internal string representation
add 1 to myString -- automatically converts to a number
add 1 to myString -- automatically converts to a number
put "The number is:" && myString
put "The number is:" && myString
-- outputs "The number is: 1235"</lang>
-- outputs "The number is: 1235"</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
Logo is weakly typed, so numeric strings can be treated as numbers and numbers can be treated as strings.
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
<syntaxhighlight lang="logo">show "123 + 1 ; 124
show word? ("123 + 1) ; true</lang>
show word? ("123 + 1) ; true</syntaxhighlight>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
<lang logtalk>number_chars(Number, "123"), Number2 is Number+1, number_chars(Number2, String2)</lang>
<syntaxhighlight lang="logtalk">number_chars(Number, "123"), Number2 is Number+1, number_chars(Number2, String2)</syntaxhighlight>


=={{header|LOLCODE}}==
=={{header|LOLCODE}}==

LOLCODE is weakly typed, so the arithmetic operators work "as expected" on strings.
LOLCODE is weakly typed, so the arithmetic operators work "as expected" on strings.


<lang LOLCODE>HAI 1.3
<syntaxhighlight lang="lolcode">HAI 1.3


I HAS A foo ITZ "1234"
I HAS A foo ITZ "1234"
Line 2,150: Line 2,204:
VISIBLE foo BTW, prints 1235
VISIBLE foo BTW, prints 1235


KTHXBYE</lang>
KTHXBYE</syntaxhighlight>


=={{header|LSL}}==
=={{header|LSL}}==
To test it yourself; rez a box on the ground, and add the following as a New Script.
To test it yourself; rez a box on the ground, and add the following as a New Script.
<lang LSL>default {
<syntaxhighlight lang="lsl">default {
state_entry() {
state_entry() {
llListen(PUBLIC_CHANNEL, "", llGetOwner(), "");
llListen(PUBLIC_CHANNEL, "", llGetOwner(), "");
Line 2,162: Line 2,216:
llOwnerSay("You said '"+sMessage+"' + 1 = "+(string)(((integer)sMessage)+1));
llOwnerSay("You said '"+sMessage+"' + 1 = "+(string)(((integer)sMessage)+1));
}
}
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Increment_a_Numerical_String: You said '99999999' + 1 = 100000000
<pre>Increment_a_Numerical_String: You said '99999999' + 1 = 100000000
Line 2,206: Line 2,260:
Val can return type using a special form, using a numeric expression as first parameter: Local m=Val(112+1.12->Decimal) make a new variable m type of decimal (96-bit integer with a variable power of 10).
Val can return type using a special form, using a numeric expression as first parameter: Local m=Val(112+1.12->Decimal) make a new variable m type of decimal (96-bit integer with a variable power of 10).


<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Module CheckIt {
s$ = "12345"
s$ = "12345"
Line 2,217: Line 2,271:
}
}
CheckIt
CheckIt
</syntaxhighlight>
</lang>


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


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


=={{header|Maple}}==
=={{header|Maple}}==
<lang maple>s := "12345";
<syntaxhighlight lang="maple">s := "12345";
s := convert(parse(s)+1, string);</lang>
s := convert(parse(s)+1, string);</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<lang Mathematica>FromDigits["1234"] + 1</lang>
<syntaxhighlight lang="mathematica">FromDigits["1234"] + 1</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
<lang MATLAB>function numStr = incrementNumStr(numStr)
<syntaxhighlight lang="matlab">function numStr = incrementNumStr(numStr)
numStr = num2str(str2double(numStr) + 1);
numStr = num2str(str2double(numStr) + 1);
end</lang>
end</syntaxhighlight>

=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
inc_string(str):=if stringp(str) and numberp(eval_string(str)) then string(eval_string(str)+1)$
"12345"$
inc_string(%);
</syntaxhighlight>
{{out}}
<pre>
"12346"
</pre>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>str = "12345"
<syntaxhighlight lang="maxscript">str = "12345"
str = ((str as integer) + 1) as string</lang>
str = ((str as integer) + 1) as string</syntaxhighlight>


=={{header|Metafont}}==
=={{header|Metafont}}==
<lang metafont>string s;
<syntaxhighlight lang="metafont">string s;
s := "1234";
s := "1234";
s := decimal(scantokens(s)+1);
s := decimal(scantokens(s)+1);
message s;</lang>
message s;</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>(int succ string) :next</lang>
<syntaxhighlight lang="min">(int succ string) :next</syntaxhighlight>

=={{header|MIPS Assembly}}==
{{trans|Z80 Assembly}}
<syntaxhighlight lang="mips">.include "\SrcAll\Header.asm" ;defines the UserRam label (address 0xA0001000 on N64)
.include "\SrcAll\BasicMacros.asm"
.include "\SrcALL\AdvancedMacros.asm"
.include "\SrcALL\MemoryMap.asm"

CursorX equ 0x100 ;offset from label UserRam, used for tracking where to print to the tv screen
CursorY equ 0x101 ;offset from label UserRam, used for tracking where to print to the tv screen
main:
;copy the string to ram.
la $t0,0x00393939 ;store 0,0x39,0x39,0x39 ;n64 is big-endian
la $t1,0x31000000
la $t2,UserRam
sw $t0,0($t2)
nop
sw $t1,4($t2)
nop
;string ram now looks like this:
; byte 0
; byte "9991"
; byte 0
; it was more convenient to store the numeric string little-endian,
; the leading terminator lets us easily print it in reverse.

la $t1,UserRam+1 ;read past the terminator placed at the front.
li $t2,0x3A
incStr:
lbu $t0,($t1)
beqz $t0,display
nop
addiu $t0,1
bltu $t0,$t2,noCarry
nop
;carry it forward
li $t0,0x30
sb $t0,($t1)
addiu $t1,1
j incStr
nop
noCarry:
sb $t0,($t1)
addiu $t1,1
j incStr
display:
la $t1,UserRam+4
display_loop:
lbu $t0,($t1)
beqz $t0,shutdown
nop
move $a1,$t0
jal PrintChar ;takes $a1 as argument, prints the ascii character in $a1 to the television screen
nop
subiu $t1,1
j display_loop
nop
shutdown:
nop ;not required on real hardware, but project 64 throws a fit if I don't have this.
b shutdown
nop</syntaxhighlight>

{{out}}
<pre>2000</pre>


=={{header|mIRC Scripting Language}}==
=={{header|mIRC Scripting Language}}==
<lang mirc>var %n = 12345
<syntaxhighlight lang="mirc">var %n = 12345
inc %n
inc %n
echo -ag %n</lang>
echo -ag %n</syntaxhighlight>


=={{header|ML}}==
=={{header|ML}}==
==={{header|mLite}}===
==={{header|mLite}}===
<lang ocaml>ntos ` ston "1234" + 1;
<syntaxhighlight lang="ocaml">ntos ` ston "1234" + 1;
</syntaxhighlight>
</lang>


==={{header|Standard ML}}===
==={{header|Standard ML}}===
<lang sml>Int.toString (1 + valOf (Int.fromString "1234"))</lang>
<syntaxhighlight lang="sml">Int.toString (1 + valOf (Int.fromString "1234"))</syntaxhighlight>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE addstr;
<syntaxhighlight lang="modula2">MODULE addstr;


IMPORT InOut, NumConv, Strings;
IMPORT InOut, NumConv, Strings;
Line 2,284: Line 2,419:
InOut.WriteString (str2);
InOut.WriteString (str2);
InOut.WriteLn
InOut.WriteLn
END addstr.</lang>
END addstr.</syntaxhighlight>
<pre>"12345" + 1 = 12346</pre>
<pre>"12345" + 1 = 12346</pre>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
Modula-3 provides the module <tt>Scan</tt> for lexing.
Modula-3 provides the module <tt>Scan</tt> for lexing.
<lang modula3>MODULE StringInt EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE StringInt EXPORTS Main;


IMPORT IO, Fmt, Scan;
IMPORT IO, Fmt, Scan;
Line 2,299: Line 2,434:
num := Scan.Int(string);
num := Scan.Int(string);
IO.Put(string & " + 1 = " & Fmt.Int(num + 1) & "\n");
IO.Put(string & " + 1 = " & Fmt.Int(num + 1) & "\n");
END StringInt.</lang>
END StringInt.</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,307: Line 2,442:
=={{header|MUMPS}}==
=={{header|MUMPS}}==
Just add. MUMPS has strings of characters as its native datatype. The "+" (plus) binary operator interprets its two arguments as numbers, so the MUMPS system does incrementing a string naturally. MUMPS portability standards require that the result must have at least 15 significant digits. Some implementations use Binary Coded Digits (BCD) and long fixed point (64 bit) integers to accomplish this.
Just add. MUMPS has strings of characters as its native datatype. The "+" (plus) binary operator interprets its two arguments as numbers, so the MUMPS system does incrementing a string naturally. MUMPS portability standards require that the result must have at least 15 significant digits. Some implementations use Binary Coded Digits (BCD) and long fixed point (64 bit) integers to accomplish this.
<syntaxhighlight lang="mumps">
<lang MUMPS>
SET STR="123"
SET STR="123"
WRITE STR+1
WRITE STR+1
</syntaxhighlight>
</lang>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>num = "123"
<syntaxhighlight lang="nanoquery">num = "123"
num = str(int(num) + 1)</lang>
num = str(int(num) + 1)</syntaxhighlight>


=={{header|Neko}}==
=={{header|Neko}}==
<lang Neko>var str = "123";
<syntaxhighlight lang="neko">var str = "123";
var str = $string($int(str) + 1);
var str = $string($int(str) + 1);


$print(str);</lang>
$print(str);</syntaxhighlight>


=={{header|Nemerle}}==
=={{header|Nemerle}}==
<lang Nemerle>mutable str = "12345";
<syntaxhighlight lang="nemerle">mutable str = "12345";
str = $"$(Int32.Parse(str)+1)";</lang>
str = $"$(Int32.Parse(str)+1)";</syntaxhighlight>


=={{header|NetRexx}}==
=={{header|NetRexx}}==
In concert with [[REXX|Rexx]], NetRexx can use typeless variables. Typeless variable support is provided through the default NetRexx <code>'''Rexx'''</code> 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.
In concert with [[REXX|Rexx]], NetRexx can use typeless variables. Typeless variable support is provided through the default NetRexx <code>'''Rexx'''</code> 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.
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */


options replace format comments java crossref savelog symbols nobinary
options replace format comments java crossref savelog symbols nobinary
Line 2,338: Line 2,473:


return
return
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,346: Line 2,481:


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>(string (++ (int "123")))</lang>
<syntaxhighlight lang="newlisp">(string (++ (int "123")))</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import strutils
<syntaxhighlight lang="nim">import strutils
let next = $(parseInt("123") + 1)</lang>
let next = $(parseInt("123") + 1)</syntaxhighlight>


=={{header|NS-HUBASIC}}==
=={{header|NS-HUBASIC}}==
<lang NS-HUBASIC>10 S$ = "12345"
<syntaxhighlight lang="ns-hubasic">10 S$ = "12345"
20 S$ = STR$(VAL(s$) + 1)</lang>
20 S$ = STR$(VAL(s$) + 1)</syntaxhighlight>


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
<lang oberon2>MODULE addstr;
<syntaxhighlight lang="oberon2">MODULE addstr;


IMPORT Out, Strings;
IMPORT Out, Strings;
Line 2,392: Line 2,527:
Out.String (str2);
Out.String (str2);
Out.Ln
Out.Ln
END addstr.</lang>
END addstr.</syntaxhighlight>
Producing:
Producing:
<pre>jan@Beryllium:~/Oberon/obc$ Add
<pre>jan@Beryllium:~/Oberon/obc$ Add
Line 2,399: Line 2,534:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang="objeck">
s := "12345";
s := "12345";
i := int->ToInt(s) + 1;
i := int->ToInt(s) + 1;
s := i->ToString();
s := i->ToString();
</syntaxhighlight>
</lang>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
<lang objc>NSString *s = @"12345";
<syntaxhighlight lang="objc">NSString *s = @"12345";
int i = [s intValue] + 1;
int i = [s intValue] + 1;
s = [NSString stringWithFormat:@"%i", i]</lang>
s = [NSString stringWithFormat:@"%i", i]</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>string_of_int (succ (int_of_string "1234"))</lang>
<syntaxhighlight lang="ocaml">string_of_int (succ (int_of_string "1234"))</syntaxhighlight>


=={{header|Octave}}==
=={{header|Octave}}==

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


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


=={{header|Oforth}}==
=={{header|Oforth}}==
+ on strings is a concatenation, not an addition. To increment, the string is converted as integer then as string again.
+ on strings is a concatenation, not an addition. To increment, the string is converted as integer then as string again.


<lang Oforth>"999" 1 + println
<syntaxhighlight lang="oforth">"999" 1 + println
"999" asInteger 1 + asString println</lang>
"999" asInteger 1 + asString println</syntaxhighlight>


{{out}}
{{out}}
Line 2,435: Line 2,569:
=={{header|OoRexx}}==
=={{header|OoRexx}}==
ooRexx supports the += etc. operators:
ooRexx supports the += etc. operators:
<lang oorexx>i=1
<syntaxhighlight lang="oorexx">i=1
i+=1
i+=1
Say i</lang>
Say i</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,444: Line 2,578:


=={{header|OpenEdge/Progress}}==
=={{header|OpenEdge/Progress}}==
<lang progress>DEFINE VARIABLE cc AS CHARACTER INITIAL "12345".
<syntaxhighlight lang="progress">DEFINE VARIABLE cc AS CHARACTER INITIAL "12345".


MESSAGE
MESSAGE
INTEGER( cc ) + 1
INTEGER( cc ) + 1
VIEW-AS ALERT-BOX.</lang>
VIEW-AS ALERT-BOX.</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>{Int.toString {String.toInt "12345"} + 1}</lang>
<syntaxhighlight lang="oz">{Int.toString {String.toInt "12345"} + 1}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>foo(s)=Str(eval(s)+1);</lang>
<syntaxhighlight lang="parigp">foo(s)=Str(eval(s)+1);</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
''See also [[#Free Pascal|Free Pascal]] and [[#Delphi|Delphi]]''
''See also [[#Free Pascal|Free Pascal]] and [[#Delphi|Delphi]]''
{{works with|Extended Pascal}}
{{works with|Extended Pascal}}
<lang pascal>type
<syntaxhighlight lang="pascal">
program TestIncNumString;
word = string(20);
type
tMyNumString = string(20);


procedure increment(var number: word);
procedure IncMyString(var NumString: tMyNumString);
var
var
i: integer;
i: integer;
begin
begin
readStr(number, i);
readStr(NumString, i);
writeStr(number, succ(i))
writeStr(NumString, succ(i))
end;</lang>
end;
//example
var
MyNumString :tMyNumString;
BEGIN
MyNumString := '12345';
write(MyNumString,' turns into ');
IncMyString(MyNumString);
write(MyNumString);
END.</syntaxhighlight>
{{out}}
<pre>12345 turns into 12346</pre>
==={{header|Free Pascal}}===
not like [[#Delphi|Delphi]] doing two conversion, but increment a string by 1 is much faster.
Here with different bases upto 10.After this there must be a correction to convert values > '9' to 'A'...
Only for positive integer strings as high speed counter.
<syntaxhighlight lang="pascal">program StrInc;
//increments a positive numerical string in different bases.
//the string must be preset with a value, length >0 ;
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
{$IFDEF FPC}
{$Mode Delphi} {$Optimization ON,ALL}{$Align 32}
uses
sysutils;
{$ELSE}
uses
system.SysUtils;
{$ENDIF}
type
myString = AnsiString; // String[32];//
function IncLoop(ps: pChar;le,Base: NativeInt):NativeInt;inline;
//Add 1 and correct carry
//returns 0, if no overflow, else 1
var
dg: nativeInt;
Begin
dec(le);//ps is 0-based
dg := ord(ps[le])+(-ord('0')+1);
result := 0;

repeat
IF dg < base then
begin
ps[le] := chr(dg+ord('0'));
EXIT;
end;
ps[le] := '0';
dec(le);
dg := ord(ps[le])+(-ord('0')+1);
until (le<0);
result:= 1;
end;
procedure IncIntStr(base:NativeInt;var s:myString);
var
le: NativeInt;
begin
le := length(s);
//overflow -> prepend a '1' to string
if (IncLoop(pChar(@s[1]),le,base) <>0) then
Begin
// s := '1'+s;
setlength(s,le+1);
move(s[1],s[2],le);
s[1] := '1';
end;
end;
const
ONE_BILLION = 1000*1000*1000;
strLen = 26;
MAX = 1 shl strLen -1;
var
s : myString;
i,base : nativeInt;
T0: TDateTime;
Begin
writeln(MAX,' increments in base');
For base := 2 to 10 do
Begin
//s := '0' doesn't work
setlength(s,1);
s[1]:= '0';
{ //Zero pad string
setlength(s,strLen);fillchar(s[1],strLen,'0');
}
T0 := time;
For i := 1 to MAX do
IncIntStr(Base,s);
T0 := (time-T0)*86400;
writeln(s:strLen,' base ',base:2,T0:8:3,' s');
end;
writeln;
writeln('One billion digits "9"');
setlength(s,ONE_BILLION+1);
s[1]:= '0';//don't measure setlength in IncIntStr
fillchar(s[2],length(s)-1,'9');
writeln('first 5 digits ',s[1],s[2],s[3],s[4],s[5]);
T0 := time;
IncIntStr(10,s);
T0 := (time-T0)*86400;
writeln(length(s):10,T0:8:3,' s');
writeln('first 5 digits ',s[1],s[2],s[3],s[4],s[5]);
s:='';
{$IFDEF WINDOWS}
readln;
{$ENDIF}
end.
</syntaxhighlight>
{{out|@TIO.RUN}}
<pre>
//sys time for allocating 1 Gb
Real time: 5.512 s User time: 4.068 s Sys. time: 1.288 s CPU share: 97.17 %

67108863 increments in base
11111111111111111111111111 base 2 0.395 s
11200021111001110 base 3 0.351 s
3333333333333 base 4 0.301 s
114134440423 base 5 0.348 s
10354213103 base 6 0.290 s
1443262443 base 7 0.281 s
377777777 base 8 0.279 s
150244043 base 9 0.271 s
67108863 base 10 0.267 s

One billion digits "9"
first 5 digits 09999
1000000001 1.382 s
first 5 digits 10000
</pre>

=={{header|Pebble}}==
<syntaxhighlight lang="pebble">program examples\incstr

data

int value[0]
str$ text['12345']

begin

strint [value],text$
+1 [value]
intstr text$,[value]

echo text$
pause
kill

end</syntaxhighlight>


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>my $s = "12345";
<syntaxhighlight lang="perl">my $s = "12345";
$s++;</lang>
$s++;</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">}}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"2047"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">}}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"2047"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
2048
2048
</pre>
</pre>

=={{header|Phixmonti}}==
<syntaxhighlight lang="phixmonti">"12345" tonum 1 + tostr</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>$s = "12345";
<syntaxhighlight lang="php">$s = "12345";
$s++;</lang>
$s++;</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
===parse_term/1===
===parse_term/1===
<code>parse_term/1</code> is the best to use if there can be no assumption of the type of the number (integer or float). For integers <code>to_int/1</code> is better to use, and for floats <code>to_float/1</code>.
<code>parse_term/1</code> is the best to use if there can be no assumption of the type of the number (integer or float). For integers <code>to_int/1</code> is better to use, and for floats <code>to_float/1</code>.
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>


% integer
% integer
Line 2,506: Line 2,799:
println(to_float=Float.to_float+1),
println(to_float=Float.to_float+1),
nl.
nl.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,519: Line 2,812:
===parse_term/3===
===parse_term/3===
<code>parse term/3</code> can evaluate numeric expressions with the help of <code>apply/1</code>:
<code>parse term/3</code> can evaluate numeric expressions with the help of <code>apply/1</code>:
<lang Picat>go2 =>
<syntaxhighlight lang="picat">go2 =>
T = "2**16+1",
T = "2**16+1",
println(t=T),
println(t=T),
parse_term(T,Term, _Vars),
parse_term(T,Term, _Vars),
println(term=Term),
println(term=Term),
println(apply=Term.apply).</lang>
println(apply=Term.apply).</syntaxhighlight>


{{out}}
{{out}}
Line 2,532: Line 2,825:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(format (inc (format "123456")))</lang>
<syntaxhighlight lang="picolisp">(format (inc (format "123456")))</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang Pike>string number = "0";
<syntaxhighlight lang="pike">string number = "0";
number = (string)((int)number+1);
number = (string)((int)number+1);
Result: "1"</lang>
Result: "1"</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>declare s picture '999999999';
<syntaxhighlight lang="pli">declare s picture '999999999';
s = '123456789';
s = '123456789';
s = s + 1;
s = s + 1;
put skip list (s);</lang>
put skip list (s);</syntaxhighlight>
<pre>
<pre>
Note:
Note:
Line 2,553: Line 2,846:


=={{header|Plain English}}==
=={{header|Plain English}}==
<lang plainenglish>To increment a numerical string:
<syntaxhighlight lang="plainenglish">To increment a numerical string:
Convert the numerical string to a number.
Convert the numerical string to a number.
Add 1 to the number.
Add 1 to the number.
Put the number into the numerical string.</lang>
Put the number into the numerical string.</syntaxhighlight>


=={{header|plainTeX}}==
=={{header|plainTeX}}==
<syntaxhighlight lang="tex">\newcount\acounter

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


The generated page will contain the text:
The generated page will contain the text:
Line 2,574: Line 2,866:


=={{header|Pop11}}==
=={{header|Pop11}}==
<lang pop11>lvars s = '123456789012123456789999999999';
<syntaxhighlight lang="pop11">lvars s = '123456789012123456789999999999';
(strnumber(s) + 1) >< '' -> s;</lang>
(strnumber(s) + 1) >< '' -> s;</syntaxhighlight>


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


=={{header|Prolog}}==
=={{header|Prolog}}==
Works with SWI-Prolog.
Works with SWI-Prolog.
<lang Prolog>incr_numerical_string(S1, S2) :-
<syntaxhighlight lang="prolog">incr_numerical_string(S1, S2) :-
string_to_atom(S1, A1),
string_to_atom(S1, A1),
atom_number(A1, N1),
atom_number(A1, N1),
Line 2,592: Line 2,884:
atom_number(A2, N2),
atom_number(A2, N2),
string_to_atom(S2, A2).
string_to_atom(S2, A2).
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<lang Prolog> ?- incr_numerical_string("123", S2).
<syntaxhighlight lang="prolog"> ?- incr_numerical_string("123", S2).
S2 = "124".
S2 = "124".
</syntaxhighlight>
</lang>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>string$="12345"
<syntaxhighlight lang="purebasic">string$="12345"
string$=Str(Val(string$)+1)
string$=Str(Val(string$)+1)
Debug string$</lang>
Debug string$</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|2.3 through 3.4}}
{{works with|Python|2.3 through 3.4}}
<lang python>next = str(int('123') + 1)</lang>
<syntaxhighlight lang="python">next = str(int('123') + 1)</syntaxhighlight>


Or, preserving the distinction between integer and floating point numeric values, while also allowing for noisy or multi-number numerical strings, and providing the option of retaining or pruning out any non-numeric parts of the string.
Or, preserving the distinction between integer and floating point numeric values, while also allowing for noisy or multi-number numerical strings, and providing the option of retaining or pruning out any non-numeric parts of the string.
<lang python># Dropping or keeping any non-numerics in the string
<syntaxhighlight lang="python"># Dropping or keeping any non-numerics in the string




Line 2,643: Line 2,935:
# MAIN ---
# MAIN ---
if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>42.0 pine martens in 1492 -0.5 mushrooms ≠ 137
<pre>42.0 pine martens in 1492 -0.5 mushrooms ≠ 137
Line 2,649: Line 2,941:


=={{header|Quackery}}==
=={{header|Quackery}}==

As a dialogue in the Quackery shell.
As a dialogue in the Quackery shell.


Line 2,674: Line 2,965:


=={{header|R}}==
=={{header|R}}==
<lang r>s = "12345"
<syntaxhighlight lang="r">s = "12345"
s <- as.character(as.numeric(s) + 1)</lang>
s <- as.character(as.numeric(s) + 1)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(define next (compose number->string add1 string->number))
(define next (compose number->string add1 string->number))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
{{works with|Rakudo|#22 "Thousand Oaks"}}


<lang perl6>my $s = "12345";
<syntaxhighlight lang="raku" line>say my $s = "12345";
say ++$s;
$s++;</lang>

# or Unicode. How about Sinhala?

say "෧෨෩෪෫ ", +"෧෨෩෪෫";
say "෧෨෩෪෫".succ, ' ', +"෧෨෩෪෫".succ;</syntaxhighlight>
{{out}}
<pre>12345
12346
෧෨෩෪෫ 12345
෧෨෩෪෬ 12346</pre>


=={{header|Rascal}}==
=={{header|Rascal}}==
<lang rascal>
<syntaxhighlight lang="rascal">
import String;
import String;


public str IncrNumStr(str s) = "<toInt(s) + 1>";
public str IncrNumStr(str s) = "<toInt(s) + 1>";
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,703: Line 3,003:


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>REBOL [
<syntaxhighlight lang="rebol">REBOL [
Title: "Increment Numerical String"
Title: "Increment Numerical String"
URL: http://rosettacode.org/wiki/Increment_numerical_string
URL: http://rosettacode.org/wiki/Increment_numerical_string
Line 2,723: Line 3,023:
print [x: "-99" "plus one equals" mold s++ x]
print [x: "-99" "plus one equals" mold s++ x]
print [x: "42" "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>
print [x: "12345" "plus one equals" mold s++ x]</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,731: Line 3,031:


=={{header|Retro}}==
=={{header|Retro}}==
<syntaxhighlight lang="retro">'123 s:to-number n:inc n:to-string</syntaxhighlight>

<lang Retro>'123 s:to-number n:inc n:to-string</lang>


=={{header|REXX}}==
=={{header|REXX}}==

REXX, like many other scripting languages, uses typeless variables.
REXX, like many other scripting languages, uses typeless variables.
<br>Typeless variables are stored as variable length character strings and can be treated as
<br>Typeless variables are stored as variable length character strings and can be treated as
<br>either a string or a numeric value, depending on the context in which they are used.
<br>either a string or a numeric value, depending on the context in which they are used.
===version 1===
===version 1===
<lang rexx>/*REXX program demonstrates a method how to increment a numerical string*/
<syntaxhighlight lang="rexx">/*REXX program demonstrates a method how to increment a numerical string*/
count = "3" /*REXX variables (and constants) are character strings.*/
count = "3" /*REXX variables (and constants) are character strings.*/
count = 3 /*(identical to the above statement.) */
count = 3 /*(identical to the above statement.) */
Line 2,760: Line 3,058:
/* [↓] show the six leftmost and rightmost digs.*/
/* [↓] show the six leftmost and rightmost digs.*/
say 'count=' left(count,6)'···'right(count,6)
say 'count=' left(count,6)'···'right(count,6)
/*stick a fork in it, we're done.*/</lang>
/*stick a fork in it, we're done.*/</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,770: Line 3,068:
Looking at the PL/I code I started investigating this situation in Rexx.
Looking at the PL/I code I started investigating this situation in Rexx.
These are my findings:
These are my findings:
<lang rexx>/* REXX ************************************************************
<syntaxhighlight lang="rexx">/* REXX ************************************************************
* There is no equivalent to PL/I's SIZE condition in REXX.
* There is no equivalent to PL/I's SIZE condition in REXX.
* The result of an arithmetic expression is rounded
* The result of an arithmetic expression is rounded
Line 2,804: Line 3,102:
Say 'LOSTDIGITS condition raised in line' sigl
Say 'LOSTDIGITS condition raised in line' sigl
Say 'sourceline='sourceline(sigl)
Say 'sourceline='sourceline(sigl)
Say "condition('D')="condition('D')</lang>
Say "condition('D')="condition('D')</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,821: Line 3,119:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
x = "1234" See 1+x # print 1235
x = "1234" See 1+x # print 1235
</syntaxhighlight>
</lang>

=={{header|RPL}}==
Conversion to/from a real number is the most convenient way to perform the task.
{{in}}
<pre>
"1234" STR→ 1 + →STR
"99.9" STR→ 1 + →STR
</pre>
{{out}}
<pre>
2: "1235"
1: "100.9"
</pre>


=={{header|Ruby}}==
=={{header|Ruby}}==
If a string represents a number, the succ method will increment the number:
If a string represents a number, the succ method will increment the number:
<lang ruby>'1234'.succ #=> '1235'
<syntaxhighlight lang="ruby">'1234'.succ #=> '1235'
'99'.succ #=> '100'</lang>
'99'.succ #=> '100'</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
Run BASIC has trim command for left and right
Run BASIC has trim command for left and right
<lang runbasic>string$ = "12345"
<syntaxhighlight lang="runbasic">string$ = "12345"
numeric = val(string$)
numeric = val(string$)
numeric = numeric + 1
numeric = numeric + 1
string$ = str$(numeric)
string$ = str$(numeric)
print string$
print string$
</syntaxhighlight>
</lang>
<pre>12346</pre>
<pre>12346</pre>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn next_string(input: &str) -> String {
<syntaxhighlight lang="rust">fn next_string(input: &str) -> String {
(input.parse::<i64>().unwrap() + 1).to_string()
(input.parse::<i64>().unwrap() + 1).to_string()
}
}
Line 2,849: Line 3,160:
let s2 = next_string(s);
let s2 = next_string(s);
println!("{:?}", s2);
println!("{:?}", s2);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>"0"</pre>
<pre>"0"</pre>
Line 2,857: Line 3,168:
handle most numeric strings. We define a method to do it.
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>
<syntaxhighlight lang="scala">implicit def toSucc(s: String) = new { def succ = BigDecimal(s) + 1 toString }</syntaxhighlight>


Usage:
Usage:
Line 2,867: Line 3,178:


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(number->string (+ 1 (string->number "1234")))</lang>
<syntaxhighlight lang="scheme">(number->string (+ 1 (string->number "1234")))</syntaxhighlight>

=={{header|Sed}}==


=={{header|sed}}==
Reads a decimal integer from stdin and outputs the same with the magnitude incremented by one.
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.)
(TODO: Since it deals only with the magnitude, the result is incorrect for negative numbers—though adding this support is definitely possible.)


The following happens:
The routine starts by suffixing the input number with a carry mark (a <code>:</code> in this case) indicating that the digit to its left still needs to be incremented. In a loop, the following happens:
* prepend zero, if only nines (there will be an overflow) or empty

* remember the number (in hold space)
* If there is a carry mark on the far left, replace it with a 1.
* increment all digits
* If there are no more carry marks, exit the loop.
* Hold the current number. (<code>h</code>)
* append the new number to the old one
* Extract the digit to the left of the first carry mark. (<code>s</code>)
* cut out everything between the two positions of the highest carry
* Replace the digit with the same digit incremented by one, with 9 incrementing to a carry mark (i.e. 10). (<code>y</code>)
* 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. (<code>s</code>)
* Retrieve the held number (<code>G</code>) and replace the first carry mark and the digit to its left with the result of the computation. (<code>s</code>)
* Repeat. (<code>b</code>)


<lang sed>s/^.*$/&:/
<syntaxhighlight lang="sed">s/^9*$/0&/
h
:bubble
y/0123456789/1234567890/
s/^:/1/
x
/.:/ {
G
h
s/^.*\(.\):.*$/\1/
s/.9*\n.*\([^0]\)/\1/</syntaxhighlight>
y/0123456789/123456789:/
s/:/:0/
G
s/\(.*\)\n\(.*\).:\(.*\)$/\2\1\3/
b bubble
}</lang>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>var string: s is "12345";
<syntaxhighlight lang="seed7">var string: s is "12345";


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


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>
<syntaxhighlight lang="sensetalk">
put "123" + 1 // 124
put "123" + 1 // 124
</syntaxhighlight>
</lang>


=={{header|SequenceL}}==
=={{header|SequenceL}}==
<lang sequencel>import <Utilities/Conversion.sl>;
<syntaxhighlight lang="sequencel">import <Utilities/Conversion.sl>;


increment(input(1)) := intToString(stringToInt(input) + 1);</lang>
increment(input(1)) := intToString(stringToInt(input) + 1);</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>say '1234'.inc; #=> '1235'
<syntaxhighlight lang="ruby">say '1234'.inc; #=> '1235'
say '99'.inc; #=> '100'</lang>
say '99'.inc; #=> '100'</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>((Integer readFrom: '123') + 1) printString</lang>
<syntaxhighlight lang="slate">((Integer readFrom: '123') + 1) printString</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==


<lang smalltalk>('123' asInteger + 1) printString</lang>
<syntaxhighlight lang="smalltalk">('123' asInteger + 1) printString</syntaxhighlight>
(a note to non-smalltalkers: "printString" does not print, but return the "printString")
(a note to non-smalltalkers: "printString" does not print, but return the "printString")


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang snobol4>
<syntaxhighlight lang="snobol4">
output = trim(input) + 1
output = trim(input) + 1
output = "123" + 1
output = "123" + 1
end</lang>
end</syntaxhighlight>


<pre>
<pre>
Line 2,940: Line 3,240:
124
124
</pre>
</pre>

=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/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 license( unrestricted );

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;</syntaxhighlight>


=={{header|Sparkling}}==
=={{header|Sparkling}}==
<lang sparkling>function numStrIncmt(s) {
<syntaxhighlight lang="sparkling">function numStrIncmt(s) {
return fmtstr("%d", toint(s) + 1);
return fmtstr("%d", toint(s) + 1);
}
}


spn:1> numStrIncmt("12345")
spn:1> numStrIncmt("12345")
= 12346</lang>
= 12346</syntaxhighlight>


=={{header|SuperTalk}}==
=={{header|SuperTalk}}==
<lang supertalk>put 0 into someVar
<syntaxhighlight lang="supertalk">put 0 into someVar
add 1 to someVar
add 1 to someVar
-- without "into [field reference]" the value will appear
-- without "into [field reference]" the value will appear
-- in the message box
-- in the message box
put someVar -- into cd fld 1</lang>
put someVar -- into cd fld 1</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
{{works with|Swift|2.x+}}
{{works with|Swift|2.x+}}
<lang swift>let s = "1234"
<syntaxhighlight lang="swift">let s = "1234"
if let x = Int(s) {
if let x = Int(s) {
print("\(x + 1)")
print("\(x + 1)")
}</lang>
}</syntaxhighlight>
{{works with|Swift|1.x}}
{{works with|Swift|1.x}}
<lang swift>let s = "1234"
<syntaxhighlight lang="swift">let s = "1234"
if let x = s.toInt() {
if let x = s.toInt() {
println("\(x + 1)")
println("\(x + 1)")
}</lang>
}</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
In the end, all variables are strings in Tcl. A "number" is merely a particular interpretation of a string of bytes.
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
<syntaxhighlight lang="tcl">set str 1234
incr str</lang>
incr str</syntaxhighlight>


=={{header|TI-83 BASIC}}==
=={{header|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.
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.
<lang ti83b>:"1"→Str1
<syntaxhighlight lang="ti83b">:"1"→Str1
:expr(Str1)+1→A
:expr(Str1)+1→A
:{0,1}→L₁
:{0,1}→L₁
Line 2,981: Line 3,301:
:LinReg(ax+b) Y₁
:LinReg(ax+b) Y₁
:Equ►String(Y₁,Str1)
:Equ►String(Y₁,Str1)
:sub(Str1,1,length(Str1)-3)→Str1</lang>
:sub(Str1,1,length(Str1)-3)→Str1</syntaxhighlight>


=={{header|TI-89 BASIC}}==
=={{header|TI-89 BASIC}}==


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


=={{header|Toka}}==
=={{header|Toka}}==
<lang toka>" 100" >number drop 1 + >string</lang>
<syntaxhighlight lang="toka">" 100" >number drop 1 + >string</syntaxhighlight>


=={{header|TorqueScript}}==
=={{header|TorqueScript}}==
Line 3,000: Line 3,320:
$string += 10;
$string += 10;
$string is now 12355.
$string is now 12355.

=={{header|Transd}}==
<syntaxhighlight lang="Scheme">
(with s "12345"
(= s String((+ (to-Int s) 1))))
(textout s))
</syntaxhighlight>
{{out}}
<pre>
12346
</pre>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
$$ MODE TUSCRIPT
teststring="0'1'-1'12345'10000000'-10000000"
teststring="0'1'-1'12345'10000000'-10000000"
Line 3,009: Line 3,340:
PRINT n
PRINT n
ENDLOOP
ENDLOOP
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,021: Line 3,352:


=={{header|TXR}}==
=={{header|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.)
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 ====
==== TXR Lisp ====


<lang txr>@(do (defun inc-num-str (str-in)
<syntaxhighlight lang="txr">@(do (defun inc-num-str (str-in)
(let ((len (length str-in))
(let ((len (length str-in))
(str (copy-str str-in)))
(str (copy-str str-in)))
Line 3,036: Line 3,366:
(set [str i] #\0))))))
(set [str i] #\0))))))
@(bind a @(inc-num-str "9999"))
@(bind a @(inc-num-str "9999"))
@(bind b @(inc-num-str "1234"))</lang>
@(bind b @(inc-num-str "1234"))</syntaxhighlight>


<pre>$ ./txr -B incnum.txr
<pre>$ ./txr -B incnum.txr
Line 3,044: Line 3,374:
==== No TXR Lisp ====
==== No TXR Lisp ====


<lang txr>@(deffilter incdig ("0" "1") ("1" "2") ("2" "3") ("3" "4") ("4" "5")
<syntaxhighlight lang="txr">@(deffilter incdig ("0" "1") ("1" "2") ("2" "3") ("3" "4") ("4" "5")
("5" "6") ("6" "7") ("7" "8") ("8" "9"))
("5" "6") ("6" "7") ("7" "8") ("8" "9"))
@(define increment (num out))
@(define increment (num out))
Line 3,064: Line 3,394:
@(end)
@(end)
@in
@in
@(increment in out)</lang>
@(increment in out)</syntaxhighlight>


<pre>$ echo 1 | ./txr -B incnum.txr -
<pre>$ echo 1 | ./txr -B incnum.txr -
Line 3,086: Line 3,416:


{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<lang bash># All variables are strings within the shell
<syntaxhighlight lang="bash"># All variables are strings within the shell
# Although num look like a number, it is in fact a numerical string
# Although num look like a number, it is in fact a numerical string
num=5
num=5
num=`expr $num + 1` # Increment the number</lang>
num=`expr $num + 1` # Increment the number</syntaxhighlight>


The [[Korn Shell]] and some newer shells do support arithmetic operations directly, and several syntax options are available:
The [[Korn Shell]] and some newer shells do support arithmetic operations directly, and several syntax options are available:
Line 3,097: Line 3,427:
{{works with|pdksh}}
{{works with|pdksh}}
{{works with|zsh}}
{{works with|zsh}}
<lang bash>num=5
<syntaxhighlight lang="bash">num=5
let num=num+1 # Increment the number
let num=num+1 # Increment the number
let "num = num + 1" # Increment again. (We can use spaces inside quotes)
let "num = num + 1" # Increment again. (We can use spaces inside quotes)
Line 3,103: Line 3,433:
let num+=1 # This time we use +=
let num+=1 # This time we use +=
let "num += 1"
let "num += 1"
((num += 1))</lang>
((num += 1))</syntaxhighlight>


{{works with|ksh93}}
{{works with|ksh93}}
{{works with|pdksh}}
{{works with|pdksh}}
{{works with|zsh}}
{{works with|zsh}}
<lang bash>integer num=5 # Declare an integer...
<syntaxhighlight lang="bash">integer num=5 # Declare an integer...
num=$num+1 # ...then increment without the let keyword.</lang>
num=$num+1 # ...then increment without the let keyword.</syntaxhighlight>


==={{header|C Shell}}===
==={{header|C Shell}}===
The <code>@</code> assignment command uses strings as integers.
The <code>@</code> assignment command uses strings as integers.
<lang csh>@ num = 5
<syntaxhighlight lang="csh">@ num = 5
@ num += 1</lang>
@ num += 1</syntaxhighlight>


=={{header|Ursa}}==
=={{header|Ursa}}==
<lang ursa>decl string num
<syntaxhighlight lang="ursa">decl string num
set num "123"
set num "123"
set num (int (+ (int num) 1))</lang>
set num (int (+ (int num) 1))</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
<syntaxhighlight lang="ursala">#import nat


instring = ~&h+ %nP+ successor+ %np@iNC # convert, do the math, convert back</syntaxhighlight>
<lang Ursala>#import nat

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


tests = instring* <'22435','4','125','77','325'></lang>
tests = instring* <'22435','4','125','77','325'></syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 3,137: Line 3,466:
=={{header|VBA}}==
=={{header|VBA}}==
The easy method assumes that the number can be represented as a Long integer:
The easy method assumes that the number can be represented as a Long integer:
<syntaxhighlight lang="vba">
<lang VBA>
Public Function incr(astring As String) As String
Public Function incr(astring As String) As String
'simple function to increment a number string
'simple function to increment a number string
incr = CStr(CLng(astring) + 1)
incr = CStr(CLng(astring) + 1)
End Function
End Function
</syntaxhighlight>
</lang>
Examples:
Examples:
<pre>
<pre>
Line 3,152: Line 3,481:


The long version handles arbitrary-length strings:
The long version handles arbitrary-length strings:
<syntaxhighlight lang="vba">
<lang VBA>
Public Function Lincr(astring As String) As String
Public Function Lincr(astring As String) As String
'increment a number string, of whatever length
'increment a number string, of whatever length
Line 3,217: Line 3,546:
decrement = result
decrement = result
End Function
End Function
</syntaxhighlight>
</lang>
Examples:
Examples:
<pre>
<pre>
Line 3,236: Line 3,565:
This example increments numeric string by converting it into numeric value, as most other language examples do.
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.
The string is located in text register 10.
<lang vedit>itoa(atoi(10)+1, 10)</lang>
<syntaxhighlight lang="vedit">itoa(atoi(10)+1, 10)</syntaxhighlight>


The following example increments unsigned numeric string of unlimited length.
The following example increments unsigned numeric string of unlimited length.
The current line in the edit buffer contains the string.
The current line in the edit buffer contains the string.
<lang vedit>EOL
<syntaxhighlight lang="vedit">EOL
do {
do {
if (At_BOL) {
if (At_BOL) {
Line 3,255: Line 3,584:
Ins_Char(#1, OVERWRITE)
Ins_Char(#1, OVERWRITE)
Char(-1)
Char(-1)
} while (#2) // repeat until no carry</lang>
} while (#2) // repeat until no carry</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
<lang vbnet> Dim s As String = "123"
<syntaxhighlight lang="vbnet"> Dim s As String = "123"


s = CStr(CInt("123") + 1)
s = CStr(CInt("123") + 1)
' or
' or
s = (CInt("123") + 1).ToString</lang>
s = (CInt("123") + 1).ToString</syntaxhighlight>


=={{header|Vlang}}==
=={{header|V (Vlang)}}==
<lang go>// Increment a numerical string in V
<syntaxhighlight lang="go">// Increment a numerical string in V
module main
module main


Line 3,281: Line 3,610:
println("numstr: $numstr")
println("numstr: $numstr")
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,293: Line 3,622:


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var ns = "41"
<syntaxhighlight lang="wren">var ns = "41"
var n = Num.fromString(ns) + 1
var n = Num.fromString(ns) + 1
var ns2 = "%(n)"
var ns2 = "%(n)"
System.print("%(ns) + 1 = %(ns2)")</lang>
System.print("%(ns) + 1 = %(ns2)")</syntaxhighlight>


{{out}}
{{out}}
Line 3,304: Line 3,633:


=={{header|XLISP}}==
=={{header|XLISP}}==
<lang lisp>(DEFUN INCREMENT-STRING (X)
<syntaxhighlight lang="lisp">(DEFUN INCREMENT-STRING (X)
(NUMBER->STRING (+ (STRING->NUMBER X) 1)))</lang>
(NUMBER->STRING (+ (STRING->NUMBER X) 1)))</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>string 0; \use zero-terminated string convention
<syntaxhighlight lang="xpl0">string 0; \use zero-terminated string convention
code Text=12;
code Text=12;


Line 3,330: Line 3,659:
IncStr(Str); IncStr(Str);
IncStr(Str); IncStr(Str);
Text(0, Str);
Text(0, Str);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 3,336: Line 3,665:
0124000000001
0124000000001
</pre>
</pre>

=={{header|Z80 Assembly}}==
As a test case, we'll start with 1999 and increment it to 2000.
<syntaxhighlight lang="z80">;;;;;;;;;;;;;;;;;;; HEADER ;;;;;;;;;;;;;;;;;;;
read "\SrcCPC\winape_macros.asm"
read "\SrcCPC\MemoryMap.asm"
read "\SrcALL\winapeBuildCompat.asm"
;;;;;;;;;;;;;;;;;;; PROGRAM ;;;;;;;;;;;;;;;;;;;

org &1000
ld hl,NumericString

incstring:
ld a,(hl)
cp 255
jr z,displaystring
add &01
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_showhex.asm"
read "\SrcCPC\winape_stringop.asm"</syntaxhighlight>

{{out}}
<pre>2000</pre>


=={{header|zkl}}==
=={{header|zkl}}==
In zkl, the first operand "wins" and transforms the second. So 5+"1"-->6
In zkl, the first operand "wins" and transforms the second. So 5+"1"-->6
<lang zkl>fcn numStringPlusOne(s){1+s}
<syntaxhighlight lang="zkl">fcn numStringPlusOne(s){1+s}
numStringPlusOne("123") //-->124</lang>
numStringPlusOne("123") //-->124</syntaxhighlight>


=={{header|Zoea}}==
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: increment_a_numerical_string
program: increment_a_numerical_string
case: 1
case: 1
Line 3,351: Line 3,729:
input: '19'
input: '19'
output: '20'
output: '20'
</syntaxhighlight>
</lang>


=={{header|Zoea Visual}}==
=={{header|Zoea Visual}}==

Latest revision as of 15:39, 23 March 2024

Task
Increment a numerical string
You are encouraged to solve this task according to the task description, using any language you may know.
Task

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
 
    ldr x0,qAdrszMessNum
    bl affichageMess
    mov x0,#STDIN          // Linux input console
    ldr x1,qAdrsBuffer     // buffer address 
    mov x2,#BUFFERSIZE     // buffer size 
    mov x8, #READ          // request to read datas
    svc 0                  // call system
    ldr x1,qAdrsBuffer     // buffer address 
    strb wzr,[x1,x0]       // store zero at the end of input string (x0
    // 
    ldr x0,qAdrsBuffer     // buffer address
    bl conversionAtoD      // conversion string in number in x0
                           // increment x0
    add x0,x0,1
                           // conversion register to string
    ldr x1,qAdrsZoneConv                
    bl conversion10S       // call conversion
    ldr x0,qAdrszMessResult
    ldr x1,qAdrsZoneConv 
    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
 
qAdrsZoneConv:          .quad sZoneConv
qAdrszMessNum:          .quad szMessNum
qAdrsBuffer:            .quad sBuffer
qAdrszMessResult:       .quad szMessResult
qAdrszCarriageReturn:   .quad szCarriageReturn
/********************************************************/
/*        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:

Screenshot from Atari 8-bit computer

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

Global $x = "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)
PRINT cadena$
END

Yabasic

cadena$ = "12345"
cadena$ = str$(val(cadena$) + 1)

IS-BASIC

100 LET S$="12345"
110 LET S$=STR$(VAL(S$)+1)

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)

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
&out$!n

   35664871829866234762193710913385490405823/6172839450617283945

Output


Bracmat also supports floating point numbers, but only in a sandboxed way. To increment 0.234E0 by 1:

(new$(UFP,(=(s.val).!val+1)).go)$"0.234e0"

Output

1.2340000000000000E+00

UFP is a new (2023) object type that specializes in compiling and executing floating point operations. Bracmat code must be passed when a UFP object is created. This code has a more restricted grammar than Bracmat code in general. The passed code must be the definition of a function that can take one or more scalars or arrays as argument. In the example, this function is (=(s.val).!val+1). The expression (s.val) says that the function takes a scalar and binds it to the local variable val. In the example, the function is defined, compiled, executed and destroyed in one go. This is not necessary; it is perfectly possible to use the compiled UFP object multiple times before destroying it.

Brat

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

Burlesque

ri?ish

C

Handling strings of arbitrary sizes:

#include <stdio.h>
#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;
}
Output:

text: +0

 ->: +1

text: -1

 ->: 0

text: -41

 ->: -40

text: +41

 ->: +42

text: 999

 ->: 1000

text: +999

 ->: 1000

text: 109999999999999999999999999999999999999999

 ->: 110000000000000000000000000000000000000000

text: -100000000000000000000000000000000000000000000

->: -99999999999999999999999999999999999999999999

C#

string s = "12345";
s = (int.Parse(s) + 1).ToString();
// The above functions properly for strings >= Int32.MinValue and
//  < Int32.MaxValue. ( -2147483648 to 2147483646 )

// The following will work for any arbitrary-length integer string.
//  (Assuming that the string fits in memory, leaving enough space
//  for the temporary BigInteger created, plus the resulting string):
using System.Numerics;
string bis = "123456789012345678999999999";
bis = (BigInteger.Parse(bis) + 1).ToString();
// Note that extremely long strings will take a long time to parse
//  and convert from a BigInteger back into a string.

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();
Works with: C++11
#include <string>

std::string s = "12345";
s = std::to_string(1+std::stoi(s));
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
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., }})
// Qt
QString num1 = "12345";
QString num2 = QString("%1").arg(v1.toInt()+1);
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., }})
// 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";
}

Ceylon

shared void run() {
	
	"Increments a numeric string by 1. Returns a float or integer depending on the string. 
	 Returns null if the string isn't a number."
	function inc(String string) => 
			if(exists integer = parseInteger(string)) then integer + 1
			else if(exists float = parseFloat(string)) then float + 1.0
			else null;
	
	value a = "1";
	print(a);
	value b = inc(a);
	print(b);
	value c = "1.0";
	print(c);
	value d = inc(c);
	print(d);
}

Clojure

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

CMake

CMake performs all arithmetic with numeric strings, through its math() command.

set(string "1599")
math(EXPR string "${string} + 1")
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[0] + " + 1= ");StdLog.Int(IncString(p.args[0]));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]));

  Readln;
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:
str = "\(parse(str) + 1)"

print(str) //Outputs 45

DWScript

var value : String = "1234";
value := IntToStr(StrToInt(value) + 1);
PrintLn(value);

Déjà Vu

 !. to-str ++ to-num "100"
Output:
"101"

E

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

EasyLang

a$ = "12"
a$ = number a$ + 1
print a$

EchoLisp

(number->string (1+ (string->number "665")))
     "666"

Ecstasy

Ecstasy provides two types that represent various numbers as if they were String values: IntLiteral and FPLiteral. For example:

String s = "12345";
IntLiteral lit1 = new IntLiteral(s);
IntLiteral lit2 = 6789;
++lit1; // lit1=12346
++lit2; // lit2=6790

Eero

#import <Foundation/Foundation.h>

int main()

  i := (int)'123' + 1
  s := @(i).description

  Log( '%@', s )
  return 0

EGL

s string = "12345";
s = 1 + s;  // Note: s + 1 is a string concatenation.

Eiffel

class
	APPLICATION

create
	make

feature {NONE}

	make
		do
			io.put_string (increment_numerical_string ("7"))
			io.new_line
			io.put_string (increment_numerical_string ("99"))
		end

	increment_numerical_string (s: STRING): STRING
			-- String 's' incremented by one.
		do
			Result := s.to_integer.plus (1).out
		end

end

Output:

8

100

Elena

ELENA 4.x:

import extensions;
 
public program()
{
    var s := "12345";
    s := (s.toInt() + 1).toString();
 
    console.printLine(s)
}
Output:
12346

Elixir

Values can be converted to integers then converted back after incrementing

increment1 = fn n -> to_string(String.to_integer(n) + 1) end
# Or piped
increment2 = fn n -> n |> String.to_integer |> +1 |> to_string end

increment1.("1")
increment2.("100")
Output:
"2"
"101"


Case of char list:

iex(1)> (List.to_integer('12345') + 1) |> to_char_list
'12346'

Emacs Lisp

(1+ (string-to-number "12345"))

EMal

fun incrementGeneric = text by generic T, text numerical 
  return text!(:T!numerical + 1) 
end
fun increment = text by text numerical
  return incrementGeneric(when(numerical.contains("."), real, int), numerical)
end
writeLine(incrementGeneric(real, "123.32"))
writeLine(incrementGeneric(int, "123"))
writeLine(increment("123.32"))
writeLine(increment("123"))
Output:
124.32
124
124.32
124

Erlang

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

ERRE

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

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

F#

// Increment a numerical string. Nigel Galloway: April 4th., 2023
let inc=int>>(+)1>>string
printfn "%s" (inc("1234"))
Output:
1235

Factor

"1234" string>number 1 + number>string

Fantom

Within 'fansh':

fansh> a := "123"
123
fansh> (a.toInt + 1).toStr
124

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

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

FreeBASIC

' FB 1.05.0 Win64

Function Increment (num As String) As String
  Dim d As Double = Val(num)
  Return Str(d + 1.0)
End Function

Dim num(5) As String = {"1", "5", "81", "123.45", "777.77", "1000"}
For i As Integer = 0 To 5
  Print num(i); " + 1", " = "; Increment(num(i))
Next

Print
Print "Press any key to exit"
Sleep
Output:
1 + 1          = 2
5 + 1          = 6
81 + 1         = 82
123.45 + 1     = 124.45
777.77 + 1     = 778.77
1000 + 1       = 1001

Frink

The following works for integers, rational numbers, complex numbers, floating-point, etc.

a = input["Enter number: "]
toString[eval[a] + 1]

FTCBASIC

define value = 0, text$ = "12345"

strint value,text$
+1 value
intstr text$,value

print text$
pause
end

FutureBasic

include "NSLog.incl"

CFStringRef s = @"12345"
NSInteger   i

for i = 1 to 10
NSLog( @"%ld", fn StringIntegerValue( s ) + i )
next
HandleEvents

Output:

 12346
 12347
 12348
 12349
 12350
 12351
 12352
 12353
 12354
 12355

Fōrmulæ

Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website.

In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.

Solution

Gambas

Click this link to run this code

Public Sub Main()
Dim vInput As Variant = "12345" 

Inc vInput
Print vInput

End

Output:

12346

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"

Go

Concise:

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

More:

package main

import (
    "math/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.ParseFloat("12.D34", 64)
    fmt.Println(err)

    // float
    fmt.Println()
    fs := "12.34"
    fmt.Println("original:   ", fs)
    f, err := strconv.ParseFloat(fs, 64)
    if err != nil {
        fmt.Println(err)
        return
    }
    // various options on FormatFloat produce different formats.  All are valid
    // input to ParseFloat, so result format does not have to match original
    // format.  (Matching original format would take more code.)
    fs = strconv.FormatFloat(f+1, 'g', -1, 64)
    fmt.Println("incremented:", fs)
    fs = strconv.FormatFloat(f+1, 'e', 4, 64)
    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

strconv.ParseInt: parsing " 1234": invalid syntax
strconv.ParseInt: parsing "12345678901": value out of range
strconv.ParseInt: parsing "_1234": invalid syntax
strconv.ParseFloat: parsing "12.D34": invalid syntax

original:    12.34
incremented: 13.34
what format? 1.3340e+01

original:    (12+34i)
incremented: (13+34i)

original:    170141183460469231731687303715884105728
incremented: 170141183460469231731687303715884105729

Golfscript

~)`

With a test framework to supply a number:

"1234" ~)` p

Groovy

Solution:

println ((("23455" as BigDecimal) + 1) as String)
println ((("23455.78" as BigDecimal) + 1) as String)
Output:
23456
23456.78

Haskell

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

or, for Integral values, we can use the Prelude's succ function:

(show . succ) (read "1234" :: Int)

and to extend the range of a succString function to allow for both floating point and integral numeric strings, for non-numeric noise, for multiple numeric expressions within a single string, and for an option to retain or prune any non-numeric noise, we could write things like:

Translation of: Python
import Text.Read (readMaybe)
import Data.Maybe (mapMaybe)

succString :: Bool -> String -> String
succString pruned s =
  let succs
        :: (Num a, Show a)
        => a -> Maybe String
      succs = Just . show . (1 +)
      go w
        | elem '.' w = (readMaybe w :: Maybe Double) >>= succs
        | otherwise = (readMaybe w :: Maybe Integer) >>= succs
      opt w
        | pruned = Nothing
        | otherwise = Just w
  in unwords $
     mapMaybe
       (\w ->
           case go w of
             Just s -> Just s
             _ -> opt w)
       (words s)


-- TEST ---------------------------------------------------
main :: IO ()
main =
  (putStrLn . unlines) $
  succString <$> [True, False] <*>
  pure "41.0 pine martens in 1491 -1.5 mushrooms ≠ 136"
Output:
42.0 1492 -0.5 137
42.0 pine martens in 1492 -0.5 mushrooms ≠ 137

HicEst

CHARACTER string = "123     -4567.89"

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

HolyC

I8 *s;

s = "10";
s = Str2I64(s) + 1;
Print("%d\n", s);

s = "-10";
s = Str2I64(s) + 1;
Print("%d\n", s);

Hy

(str (inc (int "123")))

Alternatively, with the "threading" macro:

(-> "123" (int) (inc) (str))

HyperTalk

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

i

software {
	string = "1"
	string += 1
	print(string)
}

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

IDL

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

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

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

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.

Io

str := ("123" asNumber + 1) asString

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 (though mixing these notations will coerce all values in the list to a lowest common denominator type).

   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

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

Another solution that works with big decimal numbers:

String s = "123456789012345678901234567890.12345";
s = new BigDecimal(s).add(BigDecimal.ONE).toString();

JavaScript

ES6

Using implicit coercion:

let s = '9999';
let splusplus = (+s+1)+""

console.log([splusplus, typeof splusplus]) // 10000,string

Or, expanding the range of a stringSucc function to allow for non-numeric noise, and also for multiple numeric expressions in a single string:

Translation of: Python
Translation of: Haskell
(() => {
    'use strict';

    // succString :: Bool -> String -> String
    const succString = blnPruned => s => {
        const go = w => {
            const
                v = w.includes('.') ? (
                    parseFloat(w)
                ) : parseInt(w);
            return isNaN(v) ? (
                blnPruned ? [] : [w]
            ) : [(1 + v).toString()];
        };
        return unwords(concatMap(go, words(s)));
    };

    // TEST -----------------------------------------------
    const main = () =>
        console.log(
            unlines(
                ap(
                    map(succString, [true, false]),
                    ['41 pine martens in 1491.3 -1.5 mushrooms ≠ 136']
                )
            )
        );


    // GENERIC FUNCTIONS ----------------------------------

    // Each member of a list of functions applied to each
    // of a list of arguments, deriving a list of new values.

    // ap (<*>) :: [(a -> b)] -> [a] -> [b]
    const ap = (fs, xs) => //
        fs.reduce((a, f) => a.concat(
            xs.reduce((a, x) => a.concat([f(x)]), [])
        ), []);

    // concatMap :: (a -> [b]) -> [a] -> [b]
    const concatMap = (f, xs) =>
        xs.reduce((a, x) => a.concat(f(x)), []);

    // map :: (a -> b) -> [a] -> [b]
    const map = (f, xs) => xs.map(f);

    // unlines :: [String] -> String
    const unlines = xs => xs.join('\n');

    // unwords :: [String] -> String
    const unwords = xs => xs.join(' ');

    // words :: String -> [String]
    const words = s => s.split(/\s+/);

    // MAIN ---
    return main();
})();
Output:
42 1492.3 -0.5 137
42 pine martens in 1492.3 -0.5 mushrooms ≠ 137

Joy

DEFINE incstr == 10 strtol succ 'd 1 1 format.

"1234567889" incstr.
Output:
"1234567890"

jq

tonumber

jq's string-to-number filter is called tonumber. For example, if we have a file named input.txt consisting of string representations of numbers, one per line, we could compute the sum as follows:

$ jq -n -M -s 'map(tonumber) | add' input.txt

More precisely, tonumber will convert string representations of JSON numbers (integers and decimals) to numbers, but jq version 1.6 and earlier will convert very large integers to decimals with possible loss of precision; similar problems will be noticeable for very small and very large decimals. Since the release of jq version 1.6, however, the precision of literal numbers is preserved.

The Go implementation of jq, gojq, supports unbounded-precision integer arithmetic, so for example:

$ gojq -n '"9" * 100 | tonumber + 1'
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

tostring can be used to convert numbers to strings.

long_add

# This function assumes its string arguments represent non-negative decimal integers.
def long_add(num1; num2):
  if (num1|length) < (num2|length) then long_add(num2; num1)
  else  (num1 | explode | map(.-48) | reverse) as $a1
      | (num2 | explode | map(.-48) | reverse) as $a2
      | reduce range(0; num1|length) as $ix
          ($a2;  # result
           ( $a1[$ix] + .[$ix] ) as $r
           | if $r > 9 # carrying
             then
               .[$ix + 1] = ($r / 10 | floor) +
                 (if $ix + 1 >= length then 0 else .[$ix + 1] end )
               | .[$ix] = $r - ( $r / 10 | floor ) * 10
             else
               .[$ix] = $r
             end )
      | reverse | map(.+48) | implode
  end ;

Example

long_add("9" * 100; "1")
Output:
"10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"

Jsish

var a = "1"
a = String(Number(a) + 1)

Julia

import Base.+
Base.:+(s::AbstractString, n::Real) = string((x = tryparse(Int, s)) isa Int ? x + 1 : parse(Float64, s) + 1)
@show "125" + 1
@show "125.15" + 1
@show "1234567890987654321" + 1
Output:
"125" + 1 = "126"
"125.15" + 1 = "126.15"
"1234567890987654321" + 1 = "1234567890987654322"

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

Kotlin

// version 1.0.5-2

/** overload ++ operator to increment a numeric string */
operator fun String.inc(): String =
    try {
        val num = this.toInt()
        (num + 1).toString()
    }
    catch(e: NumberFormatException) {
        this  // return string unaltered
    }

fun main(args: Array<String>) {
    var ns = "12345"
    println(++ns)
    ns = "ghijk"  // not numeric, so won't be changed by increment operator
    println(++ns)
}
Output:
12346
ghijk

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.

Lambdatalk

In lambdatalk every expression is a word or an S-expression, so:

{b hello world}     // means "boldify the words hello and world"
-> < b>hello world< /b>     // HTML expression

{+ hello world}     // means "add the words hello and world"
-> NaN              // can't do the job and returns Not a Number

{+ 123 1}           // means "add the words 123 and 1"
-> 124              // can do the job and returns the result as a word

Lang

$next $= text(+|int({{{123}}}))

Lasso

(integer('123') + 1) -> asstring

-> 124

LaTeX

\documentclass{minimal}
\newcounter{tmpnum}
\newcommand{\stringinc}[1]{%
    \setcounter{tmpnum}{#1}%
    \stepcounter{tmpnum}%
    \arabic{tmpnum}%
}
\begin{document}
The number 12345 is followed by \stringinc{12345}.
\end{document}

Liberty BASIC

'   [RC] Increment a numerical string.

o$ ="12345"
print o$

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

end

LIL

##
   Increment a numerical string, in LIL
##
set a "41"
inc a
print $a
Output:
prompt$ lil incrementNumericalString.lil
42

Lingo

put integer("123")+1
-- 124

LiveCode

LiveCode casts types transparently. When storing a number in a variable, the internal representation is numeric (a double, I think), and if the variable is used as a number, there is no type conversion. If the variable is used as a string, the conversion is automatic; likewise if a string variable containing a number is used as a number:

put "0" & "1234" into myString -- I think this will result in an internal string representation
add 1 to myString -- automatically converts to a number
put "The number is:" && myString
-- outputs "The number is: 1235"

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

Logtalk

number_chars(Number, "123"), Number2 is Number+1, number_chars(Number2, String2)

LOLCODE

LOLCODE is weakly typed, so the arithmetic operators work "as expected" on strings.

HAI 1.3

I HAS A foo ITZ "1234"
foo R SUM OF foo AN 1
VISIBLE foo BTW, prints 1235

KTHXBYE

LSL

To test it yourself; rez a box on the ground, and add the following as a New Script.

default {
	state_entry() {
		llListen(PUBLIC_CHANNEL, "", llGetOwner(), "");
		llOwnerSay("Say a Number and I'll Increment it.");
	}
	listen(integer iChannel, string sName, key kId, string sMessage) {
		llOwnerSay("You said '"+sMessage+"' + 1 = "+(string)(((integer)sMessage)+1));
	}
}
Output:
Increment_a_Numerical_String: You said '99999999' + 1 = 100000000
Increment_a_Numerical_String: You said '-100000000' + 1 = -99999999

Lua

Lua will attempt an implicit type conversion if an arithmetic operator is used with a string. This is illustrated by the following interactive session (revised for Lua 5.4):

> -- A STRING THAT CAN BE IMPLICITLY CONVERTED TO A NUMBER
> s = "1234"
> s+1 -- implicitly convert to number, add 1, remain a number
1235
> type(s+1)
number
> (s+1)..'' -- implicitly convert to number, add 1, implicitly convert back to string
1235
> type((s+1)..'')
string
> tostring(s+1) -- implicitly convert to number, add 1, explicitly convert back to string
1235
> type(tostring(s+1))
string
> -- A STRING THAT CANNOT BE IMPLICITLY CONVERTED TO A NUMBER
> s = "hello"
> s+1
stdin:1: attempt to add a 'string' with a 'number'
stack traceback:
        [C]: in metamethod 'add'
        stdin:1: in main chunk
        [C]: in ?
> -- ONE-LINER EXPLICIT VERSION
> tostring(tonumber("1234")+1)
1235

M2000 Interpreter

Using Str$( stringexpr, "") we trim leading space for positive numbers. We can use a number as locale id, 1032 for Greece, so Str$(12.1212, 1032) return without leading space "12,1212".

Str$(mumberexpression) return always dot for decimal point Val(stringexpression) read dot as decimal point Val(stringexpression, ",") use "," as decimal point Val(stringexpression, 1032) use Locale 1032 (maybe this can change by OS user), so we get "." or "," (the later is by default the decimal point for 1032).

We can use Eval("1212211212122112215@") which evaluate expressions in strings (among other duties when we use objects), and we can use letters to indicate the type of number Val can return type using a special form, using a numeric expression as first parameter: Local m=Val(112+1.12->Decimal) make a new variable m type of decimal (96-bit integer with a variable power of 10).

Module CheckIt {
      s$ = "12345"
      s$ = STR$(VAL(s$) + 1,"")
      Print S$
      \\ using , for decimal point like in Locale 1032 for Greece
      s$ = "123,45"
      \\ we get value in Locale 1032
      S$=Str$(VAL(s$,",") + 1, 1032)
}
CheckIt

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)

Maple

s := "12345";
s := convert(parse(s)+1, string);

Mathematica / Wolfram Language

FromDigits["1234"] + 1

MATLAB

function numStr = incrementNumStr(numStr)
    numStr = num2str(str2double(numStr) + 1);
end

Maxima

inc_string(str):=if stringp(str) and numberp(eval_string(str)) then string(eval_string(str)+1)$
"12345"$
inc_string(%);
Output:
"12346"

MAXScript

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

Metafont

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

min

Works with: min version 0.19.3
(int succ string) :next

MIPS Assembly

Translation of: Z80 Assembly
.include "\SrcAll\Header.asm"   ;defines the UserRam label (address 0xA0001000 on N64)
.include "\SrcAll\BasicMacros.asm"
.include "\SrcALL\AdvancedMacros.asm"
.include "\SrcALL\MemoryMap.asm"

CursorX equ 0x100 ;offset from label UserRam, used for tracking where to print to the tv screen
CursorY equ 0x101 ;offset from label UserRam, used for tracking where to print to the tv screen
main:
	;copy the string to ram.
	la $t0,0x00393939	;store 0,0x39,0x39,0x39 ;n64 is big-endian
	la $t1,0x31000000	
	
	la $t2,UserRam
	sw $t0,0($t2)
	nop
	sw $t1,4($t2)
	nop
	
	;string ram now looks like this:
	;	byte 0
	;	byte "9991"
	;	byte 0
	; it was more convenient to store the numeric string little-endian,
        ; the leading terminator lets us easily print it in reverse.
	

	la $t1,UserRam+1	;read past the terminator placed at the front.
	li $t2,0x3A
incStr:
	lbu $t0,($t1)
	beqz $t0,display
	nop
	addiu $t0,1
	bltu $t0,$t2,noCarry
	nop
	;carry it forward
	li $t0,0x30
	sb $t0,($t1)
	addiu $t1,1
	j incStr
	nop
	
noCarry:
	sb $t0,($t1)
	addiu $t1,1
	j incStr
	
display:
	la $t1,UserRam+4
display_loop:
	lbu $t0,($t1)
	beqz $t0,shutdown
	nop
	move $a1,$t0
	jal PrintChar       ;takes $a1 as argument, prints the ascii character in $a1 to the television screen
	nop
	subiu $t1,1
	j display_loop
        nop
shutdown:
	nop                 ;not required on real hardware, but project 64 throws a fit if I don't have this.
	b shutdown
	nop
Output:
2000


mIRC Scripting Language

var %n = 12345
inc %n
echo -ag %n

ML

mLite

ntos ` ston "1234" + 1;

Standard ML

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

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

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

MUMPS

Just add. MUMPS has strings of characters as its native datatype. The "+" (plus) binary operator interprets its two arguments as numbers, so the MUMPS system does incrementing a string naturally. MUMPS portability standards require that the result must have at least 15 significant digits. Some implementations use Binary Coded Digits (BCD) and long fixed point (64 bit) integers to accomplish this.

 SET STR="123"
 WRITE STR+1

Nanoquery

num = "123"
num = str(int(num) + 1)

Neko

var str = "123";
var str = $string($int(str) + 1);

$print(str);

Nemerle

mutable str = "12345";
str = $"$(Int32.Parse(str)+1)";

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

NewLISP

(string (++ (int "123")))

Nim

import strutils
let next = $(parseInt("123") + 1)

NS-HUBASIC

10 S$ = "12345"
20 S$ = STR$(VAL(s$) + 1)

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

Objeck

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

Objective-C

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

OCaml

string_of_int (succ (int_of_string "1234"))

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

Oforth

+ on strings is a concatenation, not an addition. To increment, the string is converted as integer then as string again.

"999" 1 + println
"999" asInteger 1 + asString println
Output:
9991
1000

OoRexx

ooRexx supports the += etc. operators:

i=1
i+=1
Say i
Output:
2

OpenEdge/Progress

DEFINE VARIABLE cc AS CHARACTER INITIAL "12345".

MESSAGE 
   INTEGER( cc ) + 1 
VIEW-AS ALERT-BOX.

Oz

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

PARI/GP

foo(s)=Str(eval(s)+1);

Pascal

See also Free Pascal and Delphi

Works with: Extended Pascal
program TestIncNumString;
type
	tMyNumString = string(20);

procedure IncMyString(var NumString: tMyNumString);
var
	i: integer;
begin
	readStr(NumString, i);
	writeStr(NumString, succ(i))
end;
//example 
var
  MyNumString :tMyNumString;
BEGIN
  MyNumString := '12345';
  write(MyNumString,' turns into ');
  IncMyString(MyNumString);
  write(MyNumString);
END.
Output:
12345 turns into 12346

Free Pascal

not like Delphi doing two conversion, but increment a string by 1 is much faster. Here with different bases upto 10.After this there must be a correction to convert values > '9' to 'A'... Only for positive integer strings as high speed counter.

program StrInc;
//increments a positive numerical string in different bases.
//the string must be preset with a value, length >0 ; 
{$IFDEF WINDOWS}
  {$APPTYPE CONSOLE}
{$ENDIF}
{$IFDEF FPC}
  {$Mode Delphi} {$Optimization ON,ALL}{$Align 32}
  uses
    sysutils;
{$ELSE}
  uses
    system.SysUtils;
{$ENDIF}
type
  myString =  AnsiString; // String[32];//
 
function IncLoop(ps: pChar;le,Base: NativeInt):NativeInt;inline;
//Add 1 and correct carry
//returns 0, if no overflow, else 1
var
  dg: nativeInt;
Begin
  dec(le);//ps is 0-based
  dg := ord(ps[le])+(-ord('0')+1);        
  result := 0;    

  repeat
    IF dg < base then
    begin
      ps[le] := chr(dg+ord('0'));
      EXIT;
    end; 
    ps[le] := '0';
    dec(le);
    dg := ord(ps[le])+(-ord('0')+1);        
  until (le<0);
  result:= 1;
end;
 
procedure IncIntStr(base:NativeInt;var s:myString);
var
  le: NativeInt;
begin
  le := length(s);
  //overflow -> prepend a '1' to string
  if (IncLoop(pChar(@s[1]),le,base) <>0) then
  Begin
//    s := '1'+s;
    setlength(s,le+1);
    move(s[1],s[2],le);
    s[1] := '1';
  end;  
end;
 
const
  ONE_BILLION = 1000*1000*1000;
  strLen = 26;
  MAX = 1 shl strLen -1;
 
var
  s  : myString;
  i,base : nativeInt;
  T0: TDateTime;
Begin
  writeln(MAX,' increments in base');
  For base := 2 to 10 do
  Begin
    //s := '0' doesn't work
    setlength(s,1);
    s[1]:= '0';
{   //Zero pad string
    setlength(s,strLen);fillchar(s[1],strLen,'0');
}
    T0 := time;
    For i := 1 to MAX do
      IncIntStr(Base,s);
    T0 := (time-T0)*86400;
    writeln(s:strLen,' base ',base:2,T0:8:3,' s');
  end;
 
  writeln;
  writeln('One billion digits "9"');
  setlength(s,ONE_BILLION+1);
  s[1]:= '0';//don't measure setlength in IncIntStr
  fillchar(s[2],length(s)-1,'9');
  writeln('first 5 digits ',s[1],s[2],s[3],s[4],s[5]);
  T0 := time;
  IncIntStr(10,s);
  T0 := (time-T0)*86400;
  writeln(length(s):10,T0:8:3,' s');
  writeln('first 5 digits ',s[1],s[2],s[3],s[4],s[5]);
  s:='';
  {$IFDEF WINDOWS}
    readln;
  {$ENDIF}
end.
@TIO.RUN:
//sys time for allocating 1 Gb 
Real time: 5.512 s User time: 4.068 s Sys. time: 1.288 s CPU share: 97.17 %

67108863 increments in base
11111111111111111111111111 base  2   0.395 s
         11200021111001110 base  3   0.351 s
             3333333333333 base  4   0.301 s
              114134440423 base  5   0.348 s
               10354213103 base  6   0.290 s
                1443262443 base  7   0.281 s
                 377777777 base  8   0.279 s
                 150244043 base  9   0.271 s
                  67108863 base 10   0.267 s

One billion digits "9"
first 5 digits 09999
1000000001   1.382 s
first 5 digits 10000

Pebble

program examples\incstr

data

	int value[0]
	str$ text['12345']

begin

	strint [value],text$
	+1 [value]
	intstr text$,[value]

	echo text$
	pause
	kill

end

Perl

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

Phix

integer {{n}} = scanf("2047","%d")
printf(1,"%d\n",{n+1})
Output:
2048

Phixmonti

"12345" tonum 1 + tostr

PHP

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

Picat

parse_term/1

parse_term/1 is the best to use if there can be no assumption of the type of the number (integer or float). For integers to_int/1 is better to use, and for floats to_float/1.

go =>

  % integer
  Int = "123",
  println(int=Int),
  println(parse_term=Int.parse_term+1),
  println(to_int=Int.to_int+1), % assumes integer
  nl,

  % float
  Float = "122.5",
  println(float=Float),
  println(parse_term=Float.parse_term+1),
  println(to_float=Float.to_float+1),  
  nl.
Output:
int = 123
parse_term = 124
to_int = 124

float = 122.5
parse_term = 123.5
to_float = 123.5

parse_term/3

parse term/3 can evaluate numeric expressions with the help of apply/1:

go2 =>
  T = "2**16+1",
  println(t=T),
  parse_term(T,Term, _Vars),
  println(term=Term),
  println(apply=Term.apply).
Output:
t = 2**16+1
term = 2 ** 16 + 1
apply = 65537

PicoLisp

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

Pike

string number = "0";
number = (string)((int)number+1);
Result: "1"

PL/I

declare s picture '999999999';
s = '123456789';
s = s + 1;
put skip list (s);
Note:
SIZE is enabled by default in Windows PL/I.
Therefore, with s='999999999',
the SIZE condition is raised at execution time,
and execution terminates.

Plain English

To increment a numerical string:
Convert the numerical string to a number.
Add 1 to the number.
Put the number into the numerical string.

Plain 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

The generated page will contain the text:

The number 12345 is followed by 12346.

Pop11

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

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)

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".

PureBasic

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

Python

Works with: Python version 2.3 through 3.4
next = str(int('123') + 1)

Or, preserving the distinction between integer and floating point numeric values, while also allowing for noisy or multi-number numerical strings, and providing the option of retaining or pruning out any non-numeric parts of the string.

# Dropping or keeping any non-numerics in the string


# succString :: Bool -> String -> String
def succString(blnPruned):
    def go(x):
        try:
            return [str(1 + (float(x) if '.' in x else int(x)))]
        except ValueError:
            return [] if blnPruned else [x]
    return lambda s: ' '.join(concatMap(go)(s.split()))


# TEST ----------------------------------------------------
def main():
    print(
        '\n'.join(
            [succString(bln)(
                '41.0 pine martens in 1491 -1.5 mushrooms ≠ 136'
            ) for bln in [False, True]]
        )
    )


# GENERIC ---------------------------------------------------

# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
    return lambda xs: (
        [ys[0] for ys in [f(x) for x in xs] if ys]
    )


# MAIN ---
if __name__ == '__main__':
    main()
Output:
42.0 pine martens in 1492 -0.5 mushrooms ≠ 137
42.0 1492 -0.5 137

Quackery

As a dialogue in the Quackery shell.

$->n attempts to convert a string to an integer in the current base (default is decimal). It leaves 0 (i.e. false) on the top of the data stack if the string was not a valid integer, and 1 (i.e. true) if it was. Underneath the flag is the converted integer, or the routine's best guess, if the string was not a valid integer. When the first conversion fails, we can see in the problem report that the best guess was 12345.

/O> $ "1.2.3.4.5" $->n
... not if [ $ "not a valid integer" fail ]  
... 1+
... number$ echo$
... 

       Problem: not a valid integer
Quackery Stack: 12345
  Return stack: {[...] 0} {quackery 1} {[...] 11} {shell 5} {quackery 1} {[...] 4}

/O> $ "12345" $->n
... not if [ $ "not a valid integer" fail ]  
... 1+
... number$ echo$
... 
12346
Stack empty.

R

s = "12345"
s <- as.character(as.numeric(s) + 1)

Racket

#lang racket
(define next (compose number->string add1 string->number))

Raku

(formerly Perl 6)

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

# or Unicode. How about Sinhala?

say "෧෨෩෪෫ ", +"෧෨෩෪෫";
say "෧෨෩෪෫".succ, ' ', +"෧෨෩෪෫".succ;
Output:
12345
12346
෧෨෩෪෫ 12345
෧෨෩෪෬ 12346

Rascal

import String;

public str IncrNumStr(str s) = "<toInt(s) + 1>";
Output:
rascal>IncrNumStr("123")
str: "124"

REBOL

REBOL [
	Title: "Increment Numerical String"
	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"

Retro

'123 s:to-number n:inc n:to-string

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.

version 1

/*REXX program demonstrates a method how to increment a numerical string*/
count = "3"      /*REXX variables (and constants) are character strings.*/
count =  3       /*(identical to the above statement.)                  */
count = count+1  /*strings in a numerical context are treated as numbers*/
say 'sum=' count /*display the value of  COUNT  to the terminal (screen)*/

/*────────────────── The default numeric digits for REXX is  9  digits. */
/*────────────────── However, that can be increased with NUMERIC DIGITS.*/

numeric digits 15000   /*let's go ka-razy with fifteen thousand digits. */

count=copies(2,15000)  /*stressing REXX's brains with lots of  two's,   */
                       /*the above is considered a number in REXX.      */
count=count+3          /*make that last digit of  COUNT  a  "5".        */

if 1==0  then          /*let's not display this gihugeic number to term,*/
say  'count='  count   /*ya most likely don't want to display this thing*/

                       /* [↓]  show the six leftmost and rightmost digs.*/
say  'count='  left(count,6)'···'right(count,6)
                                       /*stick a fork in it, we're done.*/
Output:
sum= 4
count= 222222···222225

version 2

Looking at the PL/I code I started investigating this situation in Rexx. These are my findings:

/* REXX ************************************************************
* There is no equivalent to PL/I's SIZE condition in REXX.
* The result of an arithmetic expression is rounded
* according to the current setting of Numeric Digits.
* ooRexx introduced, however, a LOSTDIGITS condition that checks
* if any of the OPERANDS exceeds this number of digits.
*      Unfortunately this check is currently a little too weak
*      and will not recognise a 10-digit number to be too large.
*      This little bug will be fixed in the next release of ooRexx.
**********************************************************************/
Parse Version v .
Say v
z=999999998
Do i=1 To 3
  z=z+1
  Say z
  End
Numeric Digits 20
z=999999998
Do i=1 To 3
  z=z+1
  Say z
  End
Numeric Digits 9
If left(v,11)='REXX-ooRexx' Then
  Signal On Lostdigits
z=100000000012
Say z
z=z+1
Say z
Exit
lostdigits:
  Say 'LOSTDIGITS condition raised in line' sigl
  Say 'sourceline='sourceline(sigl)
  Say "condition('D')="condition('D')
Output:
REXX-ooRexx_4.1.2(MT)
999999999
1.00000000E+9
1.00000000E+9
999999999
1000000000
1000000001
100000000012
LOSTDIGITS condition raised in line 30
sourceline=z=z+1
condition('D')= 100000000012    

Ring

x = "1234"  See 1+x  # print 1235

RPL

Conversion to/from a real number is the most convenient way to perform the task.

Input:
"1234" STR→ 1 + →STR
"99.9" STR→ 1 + →STR
Output:
2: "1235"
1: "100.9"

Ruby

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

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

Run BASIC

Run BASIC has trim command for left and right

string$ = "12345"
numeric = val(string$)
numeric = numeric + 1
string$ = str$(numeric)
print string$
12346

Rust

fn next_string(input: &str) -> String {
    (input.parse::<i64>().unwrap() + 1).to_string()
}

fn main() {
    let s = "-1";
    let s2 = next_string(s);
    println!("{:?}", s2);
}
Output:
"0"

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

Scheme

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

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 following happens:

  • prepend zero, if only nines (there will be an overflow) or empty
  • remember the number (in hold space)
  • increment all digits
  • append the new number to the old one
  • cut out everything between the two positions of the highest carry
s/^9*$/0&/
h
y/0123456789/1234567890/
x
G
s/.9*\n.*\([^0]\)/\1/

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 license( unrestricted );

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
add 1 to 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
'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

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

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 ;;;;;;;;;;;;;;;;;;;
read "\SrcCPC\winape_macros.asm"
read "\SrcCPC\MemoryMap.asm"
read "\SrcALL\winapeBuildCompat.asm"
;;;;;;;;;;;;;;;;;;; PROGRAM  ;;;;;;;;;;;;;;;;;;;

org &1000
ld hl,NumericString

incstring:
ld a,(hl)
cp 255
jr z,displaystring
add &01
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_showhex.asm"
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'

Zoea Visual

Increment a numerical string