Increment a numerical string: Difference between revisions
→{{header|FTCBASIC}}
m (→{{header|J}}) |
Basicgames (talk | contribs) Tag: Manual revert |
||
(32 intermediate revisions by 18 users not shown) | |||
Line 8:
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V next = String(Int(‘123’) + 1)</syntaxhighlight>
=={{header|8080 Assembly}}==
<
jmp demo
;;; Increment the number in the $-terminated string under HL.
Line 67 ⟶ 65:
pop d ; Print the string
mvi c,9
jmp 5</
=={{header|8086 Assembly}}==
<syntaxhighlight lang="asm"> cpu 8086
bits 16
section .text
Line 121 ⟶ 118:
mov ah,9 ; Print the string
int 21h
ret</
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program incstring64.s */
Line 194 ⟶ 191:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{Output}}
<pre>
Line 207 ⟶ 204:
=={{header|ABAP}}==
<
perform test using: '0', '1', '-1', '10000000', '-10000000'.
Line 218 ⟶ 215:
write / lv_string.
endform.
</syntaxhighlight>
{{Out}}
Line 230 ⟶ 227:
=={{header|Action!}}==
<
INT val
Line 251 ⟶ 248:
Test("-2")
Test("-10000")
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Increment_a_numerical_string.png Screenshot from Atari 8-bit computer]
Line 264 ⟶ 261:
=={{header|ActionScript}}==
<
{
return String(Number(str)+1);
}</
=={{header|Ada}}==
The standard Ada package Ada.Strings.Fixed provides a function for trimming blanks from a string.
<
S := Ada.Strings.Fixed.Trim(Source => Integer'Image(Integer'Value(S) + 1), Side => Ada.Strings.Both);</
=={{header|Aime}}==
<
o_text(itoa(atoi("2047") + 1));
o_byte('\n');
</syntaxhighlight>
=={{header|ALGOL 68}}==
Line 285 ⟶ 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]}}
{{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}}
<
associate(f, s); get(f,i);
i+:=1;
s:=""; reset(f); put(f,i);
print((s, new line))</
{{Out}}
<pre>
Line 297 ⟶ 294:
=={{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).
<
% returns a string representing the number in s incremented %
% As strings are fixed length, the significant length of s must %
Line 373 ⟶ 370:
write( " 123456789 + 1: " ); writeonToBlank( increment( "123456789", 9 ) );
write( "99999999999999999999 + 1: " ); writeonToBlank( increment( "99999999999999999999", 20 ) )
end.</
{{out}}
<pre>
Line 383 ⟶ 380:
=={{header|Apex}}==
<
string count = '12345';
count = String.valueOf(integer.valueOf(count)+1);
system.debug('Incremental Value : '+count);
</syntaxhighlight>
{{Out}}
<pre>12346</pre>
=={{header|APL}}==
<syntaxhighlight lang="apl">⍕1+⍎'12345'</syntaxhighlight>
{{Out}}
<pre>12346</pre>
=={{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:
{{Trans|Python}}
{{Trans|Haskell}}
{{Trans|JavaScript}}
<
use framework "Foundation"
use scripting additions
Line 508 ⟶ 505:
filteredArrayUsingPredicate:(ca's ¬
NSPredicate's predicateWithFormat:"0 < length")) as list
end |words|</
{{Out}}
<pre>42 1492.3 -0.5 137
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}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 719 ⟶ 796:
.align 4
.Ls_magic_number_10: .word 0x66666667
</syntaxhighlight>
=={{header|Arturo}}==
<
print ["The next number is:" (to :integer num)+1]</
{{out}}
Line 733 ⟶ 809:
=={{header|Asymptote}}==
<
cadena = string((real)cadena + 1);
write(cadena);</
{{out}}
<pre>12346.78</pre>
=={{header|AutoHotkey}}==
<
MsgBox % str += 1</
{{Out}}
<pre>12346</pre>
=={{header|AutoIt}}==
<
$x += 1
MsgBox(0,"",$x)</
{{Out}}
<pre>12346</pre>
=={{header|Avail}}==
<
incremented ::= numberString (base 10) + 1;</
=={{header|AWK}}==
The example shows that the string ''s'' can be incremented,
but after that still is a string of length 2.
<
43(2)</
=={{header|BASIC}}==
{{works with|Applesoft BASIC}}
{{works with|BaCon}}
Line 777 ⟶ 855:
{{works with|Yabasic}}
<
s$ = STR$(VAL(s$) + 1)</
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="gwbasic">S$ = "12345":S$ = STR$ ( VAL (S$) + 1)</syntaxhighlight>
==={{header|BASIC256}}===
<
cadena$ = string(val(cadena$) + 1)
#or also
cadena$ = string(FromRadix(cadena$,10) + 1)</
==={{header|OxygenBasic}}===
When a number is assigned to a string, it autoconverts.
<syntaxhighlight lang="text">
string s="122"
s=val(s)+1
print s 'result: "123"
</syntaxhighlight>
==={{header|True BASIC}}===
{{works with|QBasic}}
<
LET cadena$ = STR$(VAL(cadena$) + 1)
PRINT cadena$
END</
==={{header|Yabasic}}===
<
cadena$ = str$(val(cadena$) + 1)</
==={{header|IS-BASIC}}===
<
110 LET S$=STR$(VAL(S$)+1)</
==={{header|ZX Spectrum Basic}}===
The ZX Spectrum needs line numbers and a let statement,
but the same technique can be used:
<syntaxhighlight lang="zxbasic">10 LET s$ = "12345"
20 LET s$ = STR$(VAL(s$) + 1)</syntaxhighlight>
=={{header|Batch File}}==
Line 821 ⟶ 900:
{{works with|Windows NT|4}}
<
set /a s+=1</
=={{header|BBC BASIC}}==
This assumes the task is about incrementing an ''arbitrary-length'' decimal string.
<
REPEAT
PRINT num$
Line 843 ⟶ 922:
UNTIL A$<>"0" OR I%=0
IF A$="0" n$ = "1" + n$
ENDPROC</
=={{header|Boo}}==
<
s = (int.Parse(s) + 1).ToString()</
=={{header|BQN}}==
<
=={{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>).
<
&!n+1:?n
&out$!n
35664871829866234762193710913385490405823/6172839450617283945
</syntaxhighlight>
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}}==
<
p ("100".to_i + 1).to_s #Prints 101</
=={{header|Burlesque}}==
<syntaxhighlight lang="burlesque">
ri?ish
</syntaxhighlight>
=={{header|C}}==
Handling strings of arbitrary sizes:<
#include <string.h>
#include <stdlib.h>
Line 941 ⟶ 1,029:
return 0;
}</
{{Out}}<pre>
text: +0
Line 961 ⟶ 1,049:
=={{header|C sharp|C#}}==
<
s = (int.Parse(s) + 1).ToString();
// The above functions properly for strings >= Int32.MinValue and
Line 973 ⟶ 1,061:
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.</
=={{header|C++}}==
<
#include <cstdlib>
#include <string>
Line 991 ⟶ 1,079:
std::ostringstream oss;
if (oss << i) s = oss.str();</
{{works with|C++11}}
<
std::string s = "12345";
s = std::to_string(1+std::stoi(s));</
{{libheader|Boost}}
<
#include <cstdlib>
#include <string>
Line 1,008 ⟶ 1,096:
std::string s = "12345";
int i = boost::lexical_cast<int>(s) + 1;
s = boost::lexical_cast<std::string>(i);</
{{libheader|Qt}}
{{uses from|Library|Qt|component1=QString}}
<
QString num1 = "12345";
QString num2 = QString("%1").arg(v1.toInt()+1);</
{{Libheader|MFC}}
Line 1,020 ⟶ 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.-->
<
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++|4.0.2}}
<
#include <iostream>
#include <ostream>
Line 1,054 ⟶ 1,142:
increment_numerical_string(big_number);
std::cout << "after increment: " << big_number << "\n";
}</
=={{header|Ceylon}}==
<
"Increments a numeric string by 1. Returns a float or integer depending on the string.
Line 1,074 ⟶ 1,162:
value d = inc(c);
print(d);
}</
=={{header|Clojure}}==
<
=={{header|CMake}}==
CMake performs all arithmetic with numeric strings, through its math() command.
<
math(EXPR string "${string} + 1")
message(STATUS "${string}")</
<pre>-- 1600</pre>
=={{header|COBOL}}==
<
DATA DIVISION.
Line 1,102 ⟶ 1,190:
GOBACK
.</
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.
<
DATA DIVISION.
Line 1,117 ⟶ 1,205:
GOBACK
.</
=={{header|Common Lisp}}==
<
=={{header|Component Pascal}}==
BlackBox Component Builder
<
MODULE Operations;
IMPORT StdLog,Args,Strings;
Line 1,149 ⟶ 1,237:
END Operations.
</syntaxhighlight>
Execute: ^Q Operatiosn.DoIncString 124343~<br/>
{{Out}}
Line 1,157 ⟶ 1,245:
=={{header|D}}==
<
import std.string;
immutable s = "12349".succ;
assert(s == "12350");
}</
=={{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}}==
<
{$APPTYPE CONSOLE}
Line 1,177 ⟶ 1,272:
Readln;
end.</
{{Out}}
<pre>"12345" + 1 = 123456</pre>
=={{header|dt}}==
<syntaxhighlight lang="dt">"1234567889" to-int 1 + to-string</syntaxhighlight>
=={{header|Dyalect}}==
<
str = (parse(str) + 1).ToString()
Line 1,192 ⟶ 1,290:
str = "\(parse(str) + 1)"
print(str) //Outputs 45</
=={{header|DWScript}}==
<
value := IntToStr(StrToInt(value) + 1);
PrintLn(value);</
=={{header|Déjà Vu}}==
<
{{out}}
Line 1,206 ⟶ 1,304:
=={{header|E}}==
<
=={{header|EasyLang}}==
<syntaxhighlight lang="text">a$ = "12"
a$ = number a$ + 1
print a$</
=={{header|EchoLisp}}==
<
(number->string (1+ (string->number "665")))
→ "666"
</syntaxhighlight>
=={{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}}==
<
int main()
Line 1,229 ⟶ 1,335:
Log( '%@', s )
return 0</
=={{header|EGL}}==
<
s = 1 + s; // Note: s + 1 is a string concatenation.</
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,259 ⟶ 1,365:
end
</syntaxhighlight>
Output:
<pre>
Line 1,269 ⟶ 1,375:
=={{header|Elena}}==
ELENA 4.x:
<
public program()
Line 1,277 ⟶ 1,383:
console.printLine(s)
}</
{{out}}
<pre>
Line 1,285 ⟶ 1,391:
=={{header|Elixir}}==
Values can be converted to integers then converted back after incrementing
<
# Or piped
increment2 = fn n -> n |> String.to_integer |> +1 |> to_string end
increment1.("1")
increment2.("100")</
{{out}}
<pre>
Line 1,299 ⟶ 1,405:
'''Case of char list:'''
<
'12346'</
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(1+ (string-to-number "12345"))</syntaxhighlight>
=={{header|EMal}}==
<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}}==
<syntaxhighlight lang="erlang">integer_to_list(list_to_integer("1336")+1).</syntaxhighlight>
=={{header|ERRE}}==
<syntaxhighlight lang="text">
....................
s$="12345"
s$=STR$(VAL(s$)+1)
....................
</syntaxhighlight>
=={{header|Euphoria}}==
<
function val(sequence s)
Line 1,330 ⟶ 1,455:
s = "12345"
s = sprintf("%d",{val(s)+1})</
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// 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|Fantom}}==
Within 'fansh':
<
fansh> a := "123"
123
fansh> (a.toInt + 1).toStr
124
</syntaxhighlight>
=={{header|Forth}}==
Line 1,354 ⟶ 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.
<
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
<
over count number? not abort" invalid number"
rot s>d d+ >string rot place ;</
Test the first version like this:
<
pad inc-string
pad count type</
And the second one like this:
<
pad 1 inc-string
pad count type</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
Using 'internal' files you can increment both integer and real strings
<
INTEGER :: i
REAL :: r
Line 1,392 ⟶ 1,524:
READ(realstr, "(F10.1)") r
r = r + 1.0
WRITE(realstr, "(F10.1)") r</
=={{header|FreeBASIC}}==
<
Function Increment (num As String) As String
Line 1,409 ⟶ 1,541:
Print
Print "Press any key to exit"
Sleep</
{{out}}
Line 1,423 ⟶ 1,555:
=={{header|Frink}}==
The following works for integers, rational numbers, complex numbers, floating-point, etc.
<
toString[eval[a] + 1]</
=={{header|FTCBASIC}}==
<syntaxhighlight lang="basic">define value = 0, text$ = "12345"
strint value,text$
+1 value
intstr text$,value
print text$
pause
end</syntaxhighlight>
=={{header|FutureBasic}}==
<
include "NSLog.incl"
Line 1,437 ⟶ 1,580:
next
HandleEvents
</syntaxhighlight>
Output:
Line 1,455 ⟶ 1,598:
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Increment_a_numerical_string}}
'''Solution'''
[[File:Fōrmulæ - Increment a numerical string 01.png]]
[[File:Fōrmulæ - Increment a numerical string 02.png]]
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=e31b63f444c2c09c8b1436407020e216 Click this link to run this code]'''
<
Dim vInput As Variant = "12345"
Line 1,469 ⟶ 1,614:
Print vInput
End</
Output:
<pre>
Line 1,476 ⟶ 1,621:
=={{header|GAP}}==
<
Incr := s -> String(Int(s) + 1);
Line 1,505 ⟶ 1,650:
Increment(s);
s;
# "2400"</
=={{header|Go}}==
Concise:
<
import "fmt"
import "strconv"
Line 1,515 ⟶ 1,660:
i, _ := strconv.Atoi("1234")
fmt.Println(strconv.Itoa(i + 1))
}</
More:
<
import (
Line 1,594 ⟶ 1,739:
bs = b.Add(&b, &one).String()
fmt.Println("incremented:", bs)
}</
{{out}}
<pre>
Line 1,617 ⟶ 1,762:
=={{header|Golfscript}}==
<syntaxhighlight lang
With a test framework to supply a number:
<
=={{header|Groovy}}==
Solution:
<
println ((("23455.78" as BigDecimal) + 1) as String)</
{{Out}}
Line 1,631 ⟶ 1,776:
=={{header|Haskell}}==
<!--<
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>:
<
<
or, for Integral values, we can use the Prelude's '''succ''' function:
<
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}}
<
import Data.Maybe (mapMaybe)
Line 1,675 ⟶ 1,820:
(putStrLn . unlines) $
succString <$> [True, False] <*>
pure "41.0 pine martens in 1491 -1.5 mushrooms ≠ 136"</
{{Out}}
<pre>42.0 1492 -0.5 137
Line 1,681 ⟶ 1,826:
=={{header|HicEst}}==
<
READ( Text=string) a, b
WRITE(Text=string) a+1, b+1 ! 124 -4566.89</
=={{header|HolyC}}==
<
s = "10";
Line 1,695 ⟶ 1,840:
s = "-10";
s = Str2I64(s) + 1;
Print("%d\n", s);</
=={{header|Hy}}==
<
Alternatively, with the "threading" macro:
<
=={{header|HyperTalk}}==
<
add 1 to someVar
-- without "into [field reference]" the value will appear
-- in the message box
put someVar -- into cd fld 1</
=={{header|i}}==
<
string = "1"
string += 1
print(string)
}</
=={{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.
<
s +:= 1 # s is now an integer</
=={{header|IDL}}==
<
print, string(fix(str)+1)
;==> 1235</
In fact, IDL tries to convert types cleverly. That works, too:
<
;==> 1235</
=={{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]]).
<
To decide which indexed text is incremented (T - indexed text):
Line 1,748 ⟶ 1,893:
When play begins:
say incremented "12345";
end the story.</
=={{header|Io}}==
<syntaxhighlight lang="text">str := ("123" asNumber + 1) asString</
=={{header|J}}==
<
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).
<
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:
<
754 421
|.1+123 456
457 124</
=={{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.
<
s = String.valueOf(Integer.parseInt(s) + 1);</
Another solution that works with big decimal numbers:
<
s = new BigDecimal(s).add(BigDecimal.ONE).toString();</
=={{header|JavaScript}}==
Line 1,783 ⟶ 1,928:
Using implicit coercion:
<
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:
Line 1,792 ⟶ 1,937:
{{Trans|Python}}
{{Trans|Haskell}}
<
'use strict';
Line 1,850 ⟶ 1,995:
// MAIN ---
return main();
})();</
{{Out}}
<pre>42 1492.3 -0.5 137
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}}==
====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:
<
More precisely, <tt>tonumber</tt> will convert string representations of JSON numbers (integers and decimals) to numbers, but
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.
====long_add====
<
def long_add(num1; num2):
if (num1|length) < (num2|length) then long_add(num2; num1)
Line 1,882 ⟶ 2,040:
end )
| reverse | map(.+48) | implode
end ;</
'''Example'''
<syntaxhighlight lang="jq">
long_add("9" * 100; "1")</
{{Out}}
"10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
=={{header|Jsish}}==
<
a = String(Number(a) + 1)</
=={{header|Julia}}==
<
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
</
<pre>"125" + 1 = "126"
"125.15" + 1 = "126.15"
Line 1,908 ⟶ 2,066:
"." is a built-in function that evaluates a valid K expression.
<
1235
1 + ."1234.56"
Line 1,916 ⟶ 2,074:
inc:{1 + . x}
inc "1234"
1235</
Some other examples.
<
2 3 4 5
Line 1,926 ⟶ 2,084:
. "1","+","-10"
-9</
=={{header|Kotlin}}==
<
/** overload ++ operator to increment a numeric string */
Line 1,946 ⟶ 2,104:
ns = "ghijk" // not numeric, so won't be changed by increment operator
println(++ns)
}</
{{out}}
Line 1,954 ⟶ 2,112:
</pre>
=={{header|
{{VI snippet}}<br/>
[[File:LabVIEW_Increment_a_numerical_string.png]]
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
In lambdatalk every expression is a word or an S-expression, so:
Line 1,967 ⟶ 2,128:
{+ 123 1} // means "add the words 123 and 1"
-> 124 // can do the job and returns the result as a word
</syntaxhighlight>
=={{header|
<syntaxhighlight lang="lang">
$next $= text(+|int({{{123}}}))
</syntaxhighlight>
=={{header|Lasso}}==
<
-> 124
=={{header|LaTeX}}==
<
\newcounter{tmpnum}
\newcommand{\stringinc}[1]{%
Line 1,987 ⟶ 2,149:
\begin{document}
The number 12345 is followed by \stringinc{12345}.
\end{document}</
=={{header|Liberty BASIC}}==
<
o$ ="12345"
Line 1,999 ⟶ 2,161:
print o$
end</
=={{header|LIL}}==
<
Increment a numerical string, in LIL
##
set a "41"
inc a
print $a</
{{out}}
Line 2,014 ⟶ 2,176:
=={{header|Lingo}}==
<
-- 124</
=={{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.
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:
<
add 1 to myString -- automatically converts to a number
put "The number is:" && myString
-- outputs "The number is: 1235"</
=={{header|Logo}}==
Logo is weakly typed, so numeric strings can be treated as numbers and numbers can be treated as strings.
<
show word? ("123 + 1) ; true</
=={{header|Logtalk}}==
<
=={{header|LOLCODE}}==
LOLCODE is weakly typed, so the arithmetic operators work "as expected" on strings.
<
I HAS A foo ITZ "1234"
Line 2,043 ⟶ 2,204:
VISIBLE foo BTW, prints 1235
KTHXBYE</
=={{header|LSL}}==
To test it yourself; rez a box on the ground, and add the following as a New Script.
<
state_entry() {
llListen(PUBLIC_CHANNEL, "", llGetOwner(), "");
Line 2,055 ⟶ 2,216:
llOwnerSay("You said '"+sMessage+"' + 1 = "+(string)(((integer)sMessage)+1));
}
}</
{{Out}}
<pre>Increment_a_Numerical_String: You said '99999999' + 1 = 100000000
Line 2,099 ⟶ 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).
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
s$ = "12345"
Line 2,110 ⟶ 2,271:
}
CheckIt
</syntaxhighlight>
=={{header|M4}}==
M4 can handle only integer signed 32 bit numbers, and they can be only written as strings
<
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)
=={{header|Maple}}==
<
s := convert(parse(s)+1, string);</
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
=={{header|MATLAB}}==
<
numStr = num2str(str2double(numStr) + 1);
end</
=={{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}}==
<
str = ((str as integer) + 1) as string</
=={{header|Metafont}}==
<
s := "1234";
s := decimal(scantokens(s)+1);
message s;</
=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang
=={{header|MIPS Assembly}}==
{{trans|Z80 Assembly}}
<
.include "\SrcAll\BasicMacros.asm"
.include "\SrcALL\AdvancedMacros.asm"
Line 2,211 ⟶ 2,383:
nop ;not required on real hardware, but project 64 throws a fit if I don't have this.
b shutdown
nop</
{{out}}
Line 2,218 ⟶ 2,390:
=={{header|mIRC Scripting Language}}==
<
inc %n
echo -ag %n</
=={{header|ML}}==
==={{header|mLite}}===
<
</syntaxhighlight>
==={{header|Standard ML}}===
<
=={{header|Modula-2}}==
<
IMPORT InOut, NumConv, Strings;
Line 2,247 ⟶ 2,419:
InOut.WriteString (str2);
InOut.WriteLn
END addstr.</
<pre>"12345" + 1 = 12346</pre>
=={{header|Modula-3}}==
Modula-3 provides the module <tt>Scan</tt> for lexing.
<
IMPORT IO, Fmt, Scan;
Line 2,262 ⟶ 2,434:
num := Scan.Int(string);
IO.Put(string & " + 1 = " & Fmt.Int(num + 1) & "\n");
END StringInt.</
{{Out}}
<pre>
Line 2,270 ⟶ 2,442:
=={{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.
<syntaxhighlight lang="mumps">
SET STR="123"
WRITE STR+1
</syntaxhighlight>
=={{header|Nanoquery}}==
<
num = str(int(num) + 1)</
=={{header|Neko}}==
<
var str = $string($int(str) + 1);
$print(str);</
=={{header|Nemerle}}==
<
str = $"$(Int32.Parse(str)+1)";</
=={{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.
<
options replace format comments java crossref savelog symbols nobinary
Line 2,301 ⟶ 2,473:
return
</syntaxhighlight>
{{Out}}
<pre>
Line 2,309 ⟶ 2,481:
=={{header|NewLISP}}==
<
=={{header|Nim}}==
<
let next = $(parseInt("123") + 1)</
=={{header|NS-HUBASIC}}==
<
20 S$ = STR$(VAL(s$) + 1)</
=={{header|Oberon-2}}==
<
IMPORT Out, Strings;
Line 2,355 ⟶ 2,527:
Out.String (str2);
Out.Ln
END addstr.</
Producing:
<pre>jan@Beryllium:~/Oberon/obc$ Add
Line 2,362 ⟶ 2,534:
=={{header|Objeck}}==
<
s := "12345";
i := int->ToInt(s) + 1;
s := i->ToString();
</syntaxhighlight>
=={{header|Objective-C}}==
<
int i = [s intValue] + 1;
s = [NSString stringWithFormat:@"%i", i]</
=={{header|OCaml}}==
<
=={{header|Octave}}==
We convert the string to a number, increment it, and convert it back to a string.
<
nstring = sprintf("%d", str2num(nstring) + 1);
disp(nstring);</
=={{header|Oforth}}==
+ on strings is a concatenation, not an addition. To increment, the string is converted as integer then as string again.
<
"999" asInteger 1 + asString println</
{{out}}
Line 2,398 ⟶ 2,569:
=={{header|OoRexx}}==
ooRexx supports the += etc. operators:
<
i+=1
Say i</
{{Out}}
<pre>
Line 2,407 ⟶ 2,578:
=={{header|OpenEdge/Progress}}==
<
MESSAGE
INTEGER( cc ) + 1
VIEW-AS ALERT-BOX.</
=={{header|Oz}}==
<
=={{header|PARI/GP}}==
<
=={{header|Pascal}}==
''See also [[#Free Pascal|Free Pascal]] and [[#Delphi|Delphi]]''
{{works with|Extended Pascal}}
<
program TestIncNumString;
type
Line 2,442 ⟶ 2,613:
IncMyString(MyNumString);
write(MyNumString);
END.</
{{out}}
<pre>12345 turns into 12346</pre>
Line 2,449 ⟶ 2,620:
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.
<
//increments a positive numerical string in different bases.
//the string must be preset with a value, length >0 ;
Line 2,546 ⟶ 2,717:
{$ENDIF}
end.
</syntaxhighlight>
{{out|@TIO.RUN}}
<pre>
Line 2,568 ⟶ 2,739:
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}}==
<
$s++;</
=={{header|Phix}}==
<!--<
<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>
<!--</
{{out}}
<pre>
Line 2,584 ⟶ 2,775:
=={{header|Phixmonti}}==
<
=={{header|PHP}}==
<
$s++;</
=={{header|Picat}}==
===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>.
<
% integer
Line 2,608 ⟶ 2,799:
println(to_float=Float.to_float+1),
nl.
</syntaxhighlight>
{{out}}
Line 2,621 ⟶ 2,812:
===parse_term/3===
<code>parse term/3</code> can evaluate numeric expressions with the help of <code>apply/1</code>:
<
T = "2**16+1",
println(t=T),
parse_term(T,Term, _Vars),
println(term=Term),
println(apply=Term.apply).</
{{out}}
Line 2,634 ⟶ 2,825:
=={{header|PicoLisp}}==
<
=={{header|Pike}}==
<
number = (string)((int)number+1);
Result: "1"</
=={{header|PL/I}}==
<
s = '123456789';
s = s + 1;
put skip list (s);</
<pre>
Note:
Line 2,655 ⟶ 2,846:
=={{header|Plain English}}==
<
Convert the numerical string to a number.
Add 1 to the number.
Put the number into the numerical string.</
=={{header|plainTeX}}==
<syntaxhighlight lang="tex">\newcount\acounter
\def\stringinc#1{\acounter=#1\relax%
\advance\acounter by 1\relax%
\number\acounter}
The number 12345 is followed by \stringinc{12345}.
\bye</
The generated page will contain the text:
Line 2,676 ⟶ 2,866:
=={{header|Pop11}}==
<
(strnumber(s) + 1) >< '' -> s;</
=={{header|PowerShell}}==
The easiest way is to cast the string to int, incrementing it and casting back to string:
<
$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:
<
=={{header|Prolog}}==
Works with SWI-Prolog.
<
string_to_atom(S1, A1),
atom_number(A1, N1),
Line 2,694 ⟶ 2,884:
atom_number(A2, N2),
string_to_atom(S2, A2).
</syntaxhighlight>
{{Out}}
<
S2 = "124".
</syntaxhighlight>
=={{header|PureBasic}}==
<
string$=Str(Val(string$)+1)
Debug string$</
=={{header|Python}}==
{{works with|Python|2.3 through 3.4}}
<
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.
<
Line 2,745 ⟶ 2,935:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>42.0 pine martens in 1492 -0.5 mushrooms ≠ 137
Line 2,751 ⟶ 2,941:
=={{header|Quackery}}==
As a dialogue in the Quackery shell.
Line 2,776 ⟶ 2,965:
=={{header|R}}==
<
s <- as.character(as.numeric(s) + 1)</
=={{header|Racket}}==
<
#lang racket
(define next (compose number->string add1 string->number))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
say ++$s;
# or Unicode. How about Sinhala?
say "෧෨෩෪෫ ", +"෧෨෩෪෫";
say "෧෨෩෪෫".succ, ' ', +"෧෨෩෪෫".succ;</syntaxhighlight>
{{out}}
<pre>12345
12346
෧෨෩෪෫ 12345
෧෨෩෪෬ 12346</pre>
=={{header|Rascal}}==
<
import String;
public str IncrNumStr(str s) = "<toInt(s) + 1>";
</syntaxhighlight>
{{Out}}
<pre>
Line 2,805 ⟶ 3,003:
=={{header|REBOL}}==
<
Title: "Increment Numerical String"
URL: http://rosettacode.org/wiki/Increment_numerical_string
Line 2,825 ⟶ 3,023:
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]</
{{Out}}
Line 2,833 ⟶ 3,031:
=={{header|Retro}}==
<syntaxhighlight lang="retro">'123 s:to-number n:inc n:to-string</syntaxhighlight>
=={{header|REXX}}==
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>either a string or a numeric value, depending on the context in which they are used.
===version 1===
<
count = "3" /*REXX variables (and constants) are character strings.*/
count = 3 /*(identical to the above statement.) */
Line 2,862 ⟶ 3,058:
/* [↓] show the six leftmost and rightmost digs.*/
say 'count=' left(count,6)'···'right(count,6)
/*stick a fork in it, we're done.*/</
{{out}}
<pre>
Line 2,872 ⟶ 3,068:
Looking at the PL/I code I started investigating this situation in Rexx.
These are my findings:
<
* There is no equivalent to PL/I's SIZE condition in REXX.
* The result of an arithmetic expression is rounded
Line 2,906 ⟶ 3,102:
Say 'LOSTDIGITS condition raised in line' sigl
Say 'sourceline='sourceline(sigl)
Say "condition('D')="condition('D')</
{{Out}}
<pre>
Line 2,923 ⟶ 3,119:
=={{header|Ring}}==
<
x = "1234" See 1+x # print 1235
</syntaxhighlight>
=={{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}}==
If a string represents a number, the succ method will increment the number:
<
'99'.succ #=> '100'</
=={{header|Run BASIC}}==
Run BASIC has trim command for left and right
<
numeric = val(string$)
numeric = numeric + 1
string$ = str$(numeric)
print string$
</syntaxhighlight>
<pre>12346</pre>
=={{header|Rust}}==
<
(input.parse::<i64>().unwrap() + 1).to_string()
}
Line 2,951 ⟶ 3,160:
let s2 = next_string(s);
println!("{:?}", s2);
}</
{{out}}
<pre>"0"</pre>
Line 2,959 ⟶ 3,168:
handle most numeric strings. We define a method to do it.
<
Usage:
Line 2,969 ⟶ 3,178:
=={{header|Scheme}}==
<
=={{header|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
*
*
<
h
y/0123456789/1234567890/
x
G
=={{header|Seed7}}==
<
s := str(succ(integer parse s));</
=={{header|SenseTalk}}==
<
put "123" + 1 // 124
</syntaxhighlight>
=={{header|SequenceL}}==
<
increment(input(1)) := intToString(stringToInt(input) + 1);</
=={{header|Sidef}}==
<
say '99'.inc; #=> '100'</
=={{header|Slate}}==
<
=={{header|Smalltalk}}==
<
(a note to non-smalltalkers: "printString" does not print, but return the "printString")
=={{header|SNOBOL4}}==
<
output = trim(input) + 1
output = "123" + 1
end</
<pre>
Line 3,042 ⟶ 3,240:
124
</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}}==
<
return fmtstr("%d", toint(s) + 1);
}
spn:1> numStrIncmt("12345")
= 12346</
=={{header|SuperTalk}}==
<
add 1 to someVar
-- without "into [field reference]" the value will appear
-- in the message box
put someVar -- into cd fld 1</
=={{header|Swift}}==
{{works with|Swift|2.x+}}
<
if let x = Int(s) {
print("\(x + 1)")
}</
{{works with|Swift|1.x}}
<
if let x = s.toInt() {
println("\(x + 1)")
}</
=={{header|Tcl}}==
In the end, all variables are strings in Tcl. A "number" is merely a particular interpretation of a string of bytes.
<
incr str</
=={{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.
<
:expr(Str1)+1→A
:{0,1}→L₁
Line 3,083 ⟶ 3,301:
:LinReg(ax+b) Y₁
:Equ►String(Y₁,Str1)
:sub(Str1,1,length(Str1)-3)→Str1</
=={{header|TI-89 BASIC}}==
<syntaxhighlight lang
=={{header|Toka}}==
<
=={{header|TorqueScript}}==
Line 3,102 ⟶ 3,320:
$string += 10;
$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}}==
<
$$ MODE TUSCRIPT
teststring="0'1'-1'12345'10000000'-10000000"
Line 3,111 ⟶ 3,340:
PRINT n
ENDLOOP
</syntaxhighlight>
{{Out}}
<pre>
Line 3,123 ⟶ 3,352:
=={{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.)
==== TXR Lisp ====
<
(let ((len (length str-in))
(str (copy-str str-in)))
Line 3,138 ⟶ 3,366:
(set [str i] #\0))))))
@(bind a @(inc-num-str "9999"))
@(bind b @(inc-num-str "1234"))</
<pre>$ ./txr -B incnum.txr
Line 3,146 ⟶ 3,374:
==== No TXR Lisp ====
<
("5" "6") ("6" "7") ("7" "8") ("8" "9"))
@(define increment (num out))
Line 3,166 ⟶ 3,394:
@(end)
@in
@(increment in out)</
<pre>$ echo 1 | ./txr -B incnum.txr -
Line 3,188 ⟶ 3,416:
{{works with|Bourne 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:
Line 3,199 ⟶ 3,427:
{{works with|pdksh}}
{{works with|zsh}}
<
let num=num+1 # Increment the number
let "num = num + 1" # Increment again. (We can use spaces inside quotes)
Line 3,205 ⟶ 3,433:
let num+=1 # This time we use +=
let "num += 1"
((num += 1))</
{{works with|ksh93}}
{{works with|pdksh}}
{{works with|zsh}}
<
num=$num+1 # ...then increment without the let keyword.</
==={{header|C Shell}}===
The <code>@</code> assignment command uses strings as integers.
<
@ num += 1</
=={{header|Ursa}}==
<
set num "123"
set num (int (+ (int num) 1))</
=={{header|Ursala}}==
<syntaxhighlight lang="ursala">#import nat
instring = ~&h+ %nP+ successor+ %np@iNC # convert, do the math, convert back</syntaxhighlight>
test program:
<
tests = instring* <'22435','4','125','77','325'></
{{Out}}
<pre>
Line 3,239 ⟶ 3,466:
=={{header|VBA}}==
The easy method assumes that the number can be represented as a Long integer:
<syntaxhighlight lang="vba">
Public Function incr(astring As String) As String
'simple function to increment a number string
incr = CStr(CLng(astring) + 1)
End Function
</syntaxhighlight>
Examples:
<pre>
Line 3,254 ⟶ 3,481:
The long version handles arbitrary-length strings:
<syntaxhighlight lang="vba">
Public Function Lincr(astring As String) As String
'increment a number string, of whatever length
Line 3,319 ⟶ 3,546:
decrement = result
End Function
</syntaxhighlight>
Examples:
<pre>
Line 3,338 ⟶ 3,565:
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 following example increments unsigned numeric string of unlimited length.
The current line in the edit buffer contains the string.
<
do {
if (At_BOL) {
Line 3,357 ⟶ 3,584:
Ins_Char(#1, OVERWRITE)
Char(-1)
} while (#2) // repeat until no carry</
=={{header|Visual Basic .NET}}==
<
s = CStr(CInt("123") + 1)
' or
s = (CInt("123") + 1).ToString</
=={{header|V (Vlang)}}==
<
module main
Line 3,383 ⟶ 3,610:
println("numstr: $numstr")
}
}</
{{out}}
Line 3,395 ⟶ 3,622:
=={{header|Wren}}==
<
var n = Num.fromString(ns) + 1
var ns2 = "%(n)"
System.print("%(ns) + 1 = %(ns2)")</
{{out}}
Line 3,406 ⟶ 3,633:
=={{header|XLISP}}==
<
(NUMBER->STRING (+ (STRING->NUMBER X) 1)))</
=={{header|XPL0}}==
<
code Text=12;
Line 3,432 ⟶ 3,659:
IncStr(Str); IncStr(Str);
Text(0, Str);
]</
{{out}}
Line 3,441 ⟶ 3,668:
=={{header|Z80 Assembly}}==
As a test case, we'll start with 1999 and increment it to 2000.
<
read "\SrcCPC\winape_macros.asm"
read "\SrcCPC\MemoryMap.asm"
Line 3,483 ⟶ 3,710:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
read "\SrcCPC\winape_showhex.asm"
read "\SrcCPC\winape_stringop.asm"</
{{out}}
Line 3,490 ⟶ 3,717:
=={{header|zkl}}==
In zkl, the first operand "wins" and transforms the second. So 5+"1"-->6
<
numStringPlusOne("123") //-->124</
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
program: increment_a_numerical_string
case: 1
Line 3,502 ⟶ 3,729:
input: '19'
output: '20'
</syntaxhighlight>
=={{header|Zoea Visual}}==
|