Increment a numerical string: Difference between revisions

From Rosetta Code
Content added Content deleted
(added objective c)
Line 258: Line 258:
str = "12345"
str = "12345"
str = ((str as integer) + 1) as string
str = ((str as integer) + 1) as string

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


=={{header|OCaml}}==
=={{header|OCaml}}==

Revision as of 06:32, 14 February 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
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

BASIC

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

C

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 char s[] = "12345";
 // Using atoi
 int i = atoi(s) + 1;

 // Using strtol
 int i = (int)strtol(s, NULL, 10) + 1;
 // Using sprintf
 sprintf(s, "%d", i);

 // Using itoa (not standard)
 itoa(i, s, 10);

C++

Library: STL
 // STL with string stream operators
 #include <cstdlib>
 #include <string>
 #include <sstream>
 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();
Library: Boost
 // Boost
 #include <cstdlib>
 #include <string>
 #include <boost/lexical_cast.hpp>
 
 std::string s = "12345";
 int i = boost::lexical_cast<int>(s) + 1;
 s = boost::lexical_cast<std::string>(i);
Library: Qt
 // Qt
 QString s = "12345";
 int i = atoi((const char*)s.data()) + 1;
 // Using constructor(int, base)
 QString s2(i, 10);
 s = s2;
 // Using setNum(int)
 s.setNum(i);


Library: MFC
 // 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";
 }

C#

 string s = "12345";
 int i = int.Parse(s) + 1;
 s = i.ToString();

Common Lisp

(princ-to-string (1+ (parse-integer "1234")))

D

import std.conv, std.string;
...
auto n = toString(toInt("12345") + 1);

E

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

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 	

Haskell

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

IDL

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

J

incrTextNum=: >:&.".

or

incrTextNum=: >:&.:".

or

incrTextNum=: >:&.(_&".)

The formulation you choose depends upon the details of your desired input and ouput. Examples follow. (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.)

   incrTextNum '34.5'
35.5
   incrTextNum '7 0.2 3r5 2j4 5.7e-4'
8      
1.2    
1.6    
3j4    
1.00057

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 = (Integer.parseInt(s) + 1) + "";

JavaScript

 var s = "12345";
 var i = parseInt(s) + 1;
 s = i.toString();

A faster way instead of parseInt:

 var i = (+s)+1;
 s = i.toString()

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}

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

MAXScript

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

Objective-C

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

OCaml

string_of_int (succ (int_of_string "1234"))

Perl

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

PHP

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

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;

Python

Works with: Python version 2.3, 2.4, and 2.5
next = str(int('123') + 1)

R

s = "12345"
as.numeric(s) + 1

Ruby

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

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

Scheme

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

Seed7

 var string: s is "12345";
 s := str(succ(integer parse s));

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

Toka

" 100" >number drop 1 + >string