Increment a numerical string: Difference between revisions

(→‎{{header|Vlang}}: Rename "Vlang" in "V (Vlang)")
Tag: Manual revert
 
(29 intermediate revisions by 16 users not shown)
Line 8:
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">V next = String(Int(‘123’) + 1)</syntaxhighlight>
 
 
=={{header|8080 Assembly}}==
Line 70 ⟶ 68:
 
=={{header|8086 Assembly}}==
 
<syntaxhighlight lang="asm"> cpu 8086
bits 16
Line 392 ⟶ 389:
 
=={{header|APL}}==
 
<syntaxhighlight lang="apl">⍕1+⍎'12345'</syntaxhighlight>
{{Out}}
Line 398 ⟶ 394:
 
=={{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}}
Line 512 ⟶ 509:
<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}}==
Line 719 ⟶ 796:
.align 4
.Ls_magic_number_10: .word 0x66666667
 
</syntaxhighlight>
Line 784 ⟶ 860:
==={{header|Applesoft BASIC}}===
<syntaxhighlight lang="gwbasic">S$ = "12345":S$ = STR$ ( VAL (S$) + 1)</syntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="freebasic">cadena$ = "12345"
Line 814 ⟶ 891:
 
==={{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>
Line 857 ⟶ 932:
 
=={{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.)
<syntaxhighlight lang="bracmat">(n=35664871829866234762187538073934873121878/6172839450617283945)
&!n+1:?n
Line 864 ⟶ 939:
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}}==
Line 870 ⟶ 955:
 
=={{header|Burlesque}}==
 
<syntaxhighlight lang="burlesque">
ri?ish
Line 1,167 ⟶ 1,251:
assert(s == "12350");
}</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}}==
Line 1,185 ⟶ 1,276:
{{Out}}
<pre>"12345" + 1 = 123456</pre>
 
=={{header|dt}}==
<syntaxhighlight lang="dt">"1234567889" to-int 1 + to-string</syntaxhighlight>
 
=={{header|Dyalect}}==
Line 1,223 ⟶ 1,317:
→ "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}}==
Line 1,307 ⟶ 1,409:
 
=={{header|Emacs Lisp}}==
 
<syntaxhighlight lang="lisp">(1+ (string-to-number "12345"))</syntaxhighlight>
 
=={{header|ErlangEMal}}==
<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>
 
Line 1,337 ⟶ 1,458:
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">let next = string( int( "1234" ) + 1 )</syntaxhighlight>
// 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}}==
Line 1,343 ⟶ 1,472:
 
=={{header|Fantom}}==
 
Within 'fansh':
 
Line 1,429 ⟶ 1,557:
<syntaxhighlight lang="frink">a = input["Enter number: "]
toString[eval[a] + 1]</syntaxhighlight>
 
=={{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}}==
Line 1,459 ⟶ 1,598:
=={{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}}==
Line 1,859 ⟶ 2,000:
<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}}==
Line 1,865 ⟶ 2,013:
<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 veryjq largeversion integers1.6 and earlier will beconvert convertedvery large integers to decimals with possible loss of precision, and; 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.
 
====long_add====
<syntaxhighlight lang="jq"># This function assumes its string arguments represent non-negative decimal integers.
Line 1,958 ⟶ 2,112:
</pre>
 
=={{header|LambdatalkLabVIEW}}==
{{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,973 ⟶ 2,130:
</syntaxhighlight>
 
=={{header|LabVIEWLang}}==
<syntaxhighlight lang="lang">
{{VI snippet}}<br/>
$next $= text(+|int({{{123}}}))
[[File:LabVIEW_Increment_a_numerical_string.png]]
</syntaxhighlight>
 
=={{header|Lasso}}==
Line 2,038 ⟶ 2,196:
 
=={{header|LOLCODE}}==
 
LOLCODE is weakly typed, so the arithmetic operators work "as expected" on strings.
 
Line 2,136 ⟶ 2,293:
numStr = num2str(str2double(numStr) + 1);
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}}==
Line 2,381 ⟶ 2,549:
 
=={{header|Octave}}==
 
We convert the string to a number, increment it, and convert it back to a string.
 
Line 2,572 ⟶ 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}}==
Line 2,665 ⟶ 2,852:
 
=={{header|plainTeX}}==
 
<syntaxhighlight lang="tex">\newcount\acounter
\def\stringinc#1{\acounter=#1\relax%
Line 2,755 ⟶ 2,941:
 
=={{header|Quackery}}==
 
As a dialogue in the Quackery shell.
 
Line 2,791 ⟶ 2,976:
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|#22 "Thousand Oaks"}}
 
<syntaxhighlight lang="raku" line>say my $s = "12345";
say ++$s;
$s++;</syntaxhighlight>
 
# or Unicode. How about Sinhala?
 
say "෧෨෩෪෫ ", +"෧෨෩෪෫";
say "෧෨෩෪෫".succ, ' ', +"෧෨෩෪෫".succ;</syntaxhighlight>
{{out}}
<pre>12345
12346
෧෨෩෪෫ 12345
෧෨෩෪෬ 12346</pre>
 
=={{header|Rascal}}==
Line 2,837 ⟶ 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
Line 2,930 ⟶ 3,122:
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}}==
Line 2,975 ⟶ 3,180:
<syntaxhighlight lang="scheme">(number->string (+ 1 (string->number "1234")))</syntaxhighlight>
 
=={{header|Sedsed}}==
 
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:
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)
* increment all digits
* append the new number to the old one
* cut out everything between the two positions of the highest carry
 
<syntaxhighlight lang="sed">s/^9*$/0&/
* If there is a carry mark on the far left, replace it with a 1.
h
* If there are no more carry marks, exit the loop.
y/0123456789/1234567890/
* Hold the current number. (<code>h</code>)
x
* Extract the digit to the left of the first carry mark. (<code>s</code>)
G
* Replace the digit with the same digit incremented by one, with 9 incrementing to a carry mark (i.e. 10). (<code>y</code>)
s/.9*\n.*\([^0]\)/\1/</syntaxhighlight>
* 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>)
 
<syntaxhighlight lang="sed">s/^.*$/&:/
:bubble
s/^:/1/
/.:/ {
h
s/^.*\(.\):.*$/\1/
y/0123456789/123456789:/
s/:/:0/
G
s/\(.*\)\n\(.*\).:\(.*\)$/\2\1\3/
b bubble
}</syntaxhighlight>
 
=={{header|Seed7}}==
Line 3,046 ⟶ 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}}==
Line 3,106 ⟶ 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}}==
Line 3,127 ⟶ 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.)
 
Line 3,228 ⟶ 3,452:
 
=={{header|Ursala}}==
 
<syntaxhighlight lang="ursala">#import nat
 
Line 3,399 ⟶ 3,622:
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascriptwren">var ns = "41"
var n = Num.fromString(ns) + 1
var ns2 = "%(n)"
305

edits