Increment a numerical string: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added Oz example.)
Line 341: Line 341:
disp(nstring);</lang>
disp(nstring);</lang>


=={{header|Oz}}==

<lang oz>{Int.toString {String.toInt "12345"} + 1}</lang>
=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>my $s = "12345";
<lang perl>my $s = "12345";

Revision as of 16:46, 13 December 2009

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

This task is about incrementing a numerical string.

Ada

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

ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386

<lang algol68>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))</lang> Output: <lang algol68>+12346</lang>

AutoHotkey

<lang autohotkey>str = 12345 MsgBox % str += 1</lang> Output:

12346

AWK

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


BASIC

Works with: QuickBasic version 4.5
Works with: PowerBASIC
 s$ = "12345"
 s$ = STR$(VAL(s$) + 1)

C

<lang c>#include <stdio.h>

  1. include <stdlib.h>
  2. include <string.h>

char* int2str(int value, char *bufr) {

   static char buf[32];
   static char digits[]="0123456789";
   int i = 30;
   if (bufr==NULL) bufr = buf;
   for(; value && i ; --i, value /= 10)

bufr[i] = digits[value % 10];

   return &bufr[i+1];

}

int main(int argc, char *argv[]) {

  char s[] = "12345";
  char rbuf[32];
  char *result;
  int   temp;
  // Using atoi and int2str (above)
  result = int2str(atoi(s)+1, rbuf);
  // Using strtol
  temp = (int)strtol(s, NULL, 10) + 1;
  result = int2str(temp, NULL);
  // Using sprintf/sscanf
  sscanf(s, "%d", &temp);
  sprintf(rbuf, "%d", temp+1 );
  result = rbuf;
  // Using itoa (not standard)
  result = itoa(temp+1, rbuf, 10);
  return 0;

}</lang>

C++

Library: STL

<lang cpp>// STL with string stream operators

  1. include <cstdlib>
  2. include <string>
  3. 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();</lang>

Library: Boost

<lang cpp>// Boost

  1. include <cstdlib>
  2. include <string>
  3. 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);</lang>

Library: Qt

<lang cpp>// Qt QString num1 = "12345"; QString num2 = QString("%1").arg(v1.toInt()+1);</lang>

Library: MFC

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

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

<lang cpp>#include <string>

  1. include <iostream>
  2. 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";

}</lang>

C#

<lang csharp>string s = "12345"; int i = int.Parse(s) + 1; s = i.ToString();</lang>

Clojure

<lang lisp>(str (inc (Integer/parseInt "1234")))</lang>

Common Lisp

<lang lisp>(princ-to-string (1+ (parse-integer "1234")))</lang>

D

<lang d>import std.conv, std.string; ... auto n = toString(toInt("12345") + 1);</lang>

E

<lang e>__makeInt("1234", 10).next().toString(10)</lang>

Erlang

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

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.

<lang forth>: >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 ;</lang>

Here is a version that can increment by any value

<lang forth>: inc-string ( addr n -- )

 over count number? not abort" invalid number"
 rot s>d d+  >string rot place ;</lang>

Test the first version like this:

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

And the second one like this:

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

Fortran

Works with: Fortran version 90 and later

Using 'internal' files you can increment both integer and real strings <lang fortran>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</lang>


Groovy

Solution: <lang groovy>println ((("23455" as BigDecimal) + 1) as String) println ((("23455.78" as BigDecimal) + 1) as String)</lang>

Output:

23456
23456.78

Haskell

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

IDL

<lang idl>str = '1234' print, string(fix(str)+1)

==> 1235</lang>

J

<lang j>incrTextNum=: >:&.".</lang>

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. <lang j> incrTextNum '34.5' 35.5

  incrTextNum '7 0.2 3r5 2j4 5.7e_4'

8 1.2 1.6 3j4 1.00057</lang>

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. <lang java>String s = "12345"; s = (Integer.parseInt(s) + 1) + "";</lang>

JavaScript

<lang javascript>var s = "12345"; var i = parseInt(s, 10) + 1; s = i.toString();</lang>

A faster way instead of parseInt:

<lang javascript>var i = (+s)+1; s = i.toString()</lang>

LaTeX

<lang latex>\documentclass{article}

% numbers are stored in counters \newcounter{tmpnum}

% macro to increment a string (given as argument) \newcommand{\stringinc}[1]{% \setcounter{tmpnum}{#1}% setcounter effectively converts the string to a number \stepcounter{tmpnum}% increment the counter; alternatively: \addtocounter{tmpnum}{1} \arabic{tmpnum}% convert counter value to arabic (i.e. decimal) number string }

%example usage \begin{document} The number 12345 is followed by \stringinc{12345}. \end{document}</lang>

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 show word? ("123 + 1) ; true</lang>

Lua

<lang lua>print(tonumber("2345")+1)</lang>

M4

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

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)

MAXScript

<lang maxscript>str = "12345" str = ((str as integer) + 1) as string</lang>

Metafont

<lang metafont>string s; s := "1234"; s := decimal(scantokens(s)+1); message s;</lang>

Modula-3

Modula-3 provides the module Scan for lexing. <lang modula3>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.</lang> Output:

1234 + 1 = 1235

Objective-C

<lang objc>NSString *s = @"12345"; int i = [s intValue] + 1; s = [NSString stringWithFormat:@"%i", i]</lang>

OCaml

<lang ocaml>string_of_int (succ (int_of_string "1234"))</lang>

Octave

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

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

Oz

<lang oz>{Int.toString {String.toInt "12345"} + 1}</lang>

Perl

<lang perl>my $s = "12345"; $s++;</lang>

Perl 6

Works with: Rakudo version #22 "Thousand Oaks"

<lang perl6>my $s = "12345"; $s++;</lang>

PHP

<lang php>$s = "12345"; $s++;</lang>

Plain TeX

<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</lang>

The generated page will contain the text:

The number 12345 is followed by 12346.

Pop11

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

PowerShell

The easiest way is to cast the string to int, incrementing it and casting back to string: <lang powershell>$s = "12345" $t = [string] ([int] $s + 1)</lang> 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>

Python

Works with: Python version 2.3, 2.4, and 2.5

<lang python>next = str(int('123') + 1)</lang>

R

<lang r>s = "12345" as.numeric(s) + 1</lang>

Ruby

If a string represents a number, the succ method will increment the number: <lang ruby>'1234'.succ #=> '1235' '99'.succ #=> '100'</lang>

Scheme

<lang scheme>(number->string (+ 1 (string->number "1234")))</lang>

Seed7

<lang seed7>var string: s is "12345";

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

Slate

<lang slate>((Integer readFrom: '123') + 1) printString</lang>

Smalltalk

<lang smalltalk>('123' asInteger + 1) printString</lang>

Standard ML

<lang sml>Int.toString (1 + valOf (Int.fromString "1234"))</lang>

Tcl

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 incr str</lang>

TI-89 BASIC

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

Toka

<lang toka>" 100" >number drop 1 + >string</lang>

Ursala

<lang Ursala>#import nat

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

tests = instring* <'22435','4','125','77','325'></lang> output:

<'22436','5','126','78','326'>


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. <lang vedit>itoa(atoi(10)+1, 10)</lang>

The following example increments unsigned numeric string of unlimited length. The current line in the edit buffer contains the string. <lang vedit>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</lang>