Recent

Author Topic: The sum of numbers in a string  (Read 15477 times)

mstriker23

  • Newbie
  • Posts: 2
The sum of numbers in a string
« on: January 25, 2015, 07:53:32 pm »
Hello!

Could anyone please help me? I need to get the sum of numbers that are in a string, each number are seperated by a space.

For example, the string is '150 20 100 10 1'. Now how to sum these numbers (150+20+100+10+1) to get the answer? %)
« Last Edit: January 25, 2015, 07:57:06 pm by mstriker23 »

engkin

  • Hero Member
  • *****
  • Posts: 3112
Re: The sum of numbers in a string
« Reply #1 on: January 25, 2015, 07:57:40 pm »
Is this an assignment/homework?  O:-)

Edit:
If not:
Code: [Select]
program Project1;

{$MODE objfpc}

uses
  sysutils, Classes;

var
  Strs: TStringList;
  i,Total: integer;

begin
  Strs:= TStringList.Create;
  try
    Strs.Delimiter:=' ';
    Strs.DelimitedText:='150 20 100 10 1';

    Total := 0;
    for i := 0 to Strs.Count-1 do
      try
        Total := Total + StrToInt(Strs[i]);
      except
        on E: EConvertError do WriteLn('Error: Cannot convert ', Strs[i],' to number');
      end;

    WriteLn('Total: ',Total);

    ReadLn();
  finally
    Strs.Free;
  end;
end.
« Last Edit: January 25, 2015, 09:03:20 pm by engkin »

mstriker23

  • Newbie
  • Posts: 2
Re: The sum of numbers in a string
« Reply #2 on: January 25, 2015, 09:41:46 pm »
Thanks for your help, engkin. It's not a homework, but a small part of the whole program. :)

Ok, so this is the only solution, and there aren't other ways to solve this? Because I'm not familiar with the TStringList.

typo

  • Hero Member
  • *****
  • Posts: 3051
Re: The sum of numbers in a string
« Reply #3 on: January 25, 2015, 09:49:29 pm »
As you can see, TStringList is the simplest way of breaking a string on spaces or some repetitive character. After that, you simply sum the lines converted to integer.

wp

  • Hero Member
  • *****
  • Posts: 11923
Re: The sum of numbers in a string
« Reply #4 on: January 25, 2015, 10:02:52 pm »
Or do it manually (not tested) - try to understand what is going on here...:
Code: [Select]
function AddNumbersInString(AString: string): Integer;
var
  p: Integer;
  s: String;
begin
  Result := 0;
  while AString <> '' do begin
    p := pos(' ', AString);   // Find the first SPACE
    if p > 0 then begin       // Found!
      s := Copy(AString, 1, p-1);       // Extract the part of the string to the SPACE
      Result := Result + StrToInt(s);   // Convert to number and add
      AString := Copy(AString, p+1, Length(s));  // Continue with the rest of the string after the SPACE
    end else begin           // No space --> String is only a single number
      Result := Result + StrToInt(AString);    // Convert to number and add
      AString := '';         // This signals that the loop should terminate.
    end;
  end;
end;

engkin

  • Hero Member
  • *****
  • Posts: 3112
Re: The sum of numbers in a string
« Reply #5 on: January 25, 2015, 10:17:38 pm »
so this is the only solution, and there aren't other ways to solve this?

No, you can use something else like regular expressions:
Code: [Select]
program Project1;

uses
 RegExpr, SysUtils;

var
  re: TRegExpr;
  Total: integer;
begin
  Total := 0;

  re := TRegExpr.Create;
  try
    re.Expression := '(\d+)';
    if re.Exec('150 20 100 10 1') then
      repeat
        Total := Total + StrToInt(re.Match[1]);
      until not re.ExecNext;
  finally
    re.Free;
  end;

  WriteLn('Total: ', Total);
  ReadLn;
end.

Never

  • Sr. Member
  • ****
  • Posts: 409
  • OS:Win7 64bit / Lazarus 1.4
Re: The sum of numbers in a string
« Reply #6 on: January 25, 2015, 11:47:20 pm »
hello,
there is ArtFormula user: [ Art ]  [ http://forum.lazarus.freepascal.org/index.php?topic=18003.0 ]
i think is what are you looking for
Νέπε Λάζαρε λάγγεψων οξωκά ο φίλοσ'ς αραεύσε

howardpc

  • Hero Member
  • *****
  • Posts: 4144
Re: The sum of numbers in a string
« Reply #7 on: January 25, 2015, 11:54:48 pm »
Ok, so this is the only solution, and there aren't other ways to solve this?

Or you can roll your own parsing routine. If you restrict yourself to strings containing only ASCII characters this is not too difficult.
Code: [Select]
program Project1;

uses
 SysUtils;

var
  s: string;
  Total: integer = 0;
  Start: integer = 1;
  p: integer;

const
  NumberStr: string = '150 20 100 10 1';

  function CopyWordPos(aStart: integer; const aText: string; aDelim: Char; var aNext: integer): string;
  var
    len: integer;
  begin
    aNext:=aStart;
    len:=Length(aText);
    while (aNext <= len) and (aText[aNext] <> aDelim) do
      Inc(aNext);
    Result:=Copy(aText, aStart, aNext-aStart);
    Inc(aNext);
  end;

begin
  repeat
    s:=CopyWordPos(Start, NumberStr, ' ', p);
    if (s <> '') then
      begin
        Inc(Total, StrToIntDef(s, 0));
        Start:=p;
      end;
  until (s = '');
  WriteLn('Total: ', Total);
  ReadLn;
end.


djzepi

  • New Member
  • *
  • Posts: 36
Re: The sum of numbers in a string
« Reply #8 on: January 26, 2015, 08:49:03 am »
...
uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
  fpexprpars;

{ TForm1 }

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
var
  s, after: String;
  FParser: TFPExpressionParser;
  resultValue: integer;

begin
  s:= '150 20 100 10 1';
  after  := StringReplace(s, ' ', '+', [rfReplaceAll, rfIgnoreCase]);
  FParser := TFPExpressionParser.Create(nil);
    try
      FParser.BuiltIns := [bcMath];
      FParser.Expression := after;
      resultValue := FParser.Evaluate.ResInteger;
      Memo1.Lines.Add( FParser.Expression + ' = ' + IntToStr(resultValue));
    finally
      FParser.Free;
    end;
end;

Linkat

  • New Member
  • *
  • Posts: 19
Re: The sum of numbers in a string
« Reply #9 on: January 26, 2015, 09:21:18 am »
Hi mstriker23,
In the unit 'StrUtils' is the function ExtractDelimited.

Here is an example:

Code: [Select]
uses StrUtils;

procedure TForm1.FormCreate(Sender: TObject);
var i,j,sum          :Integer;
    s1,s2            :String;
begin
  s1:='150 250 120 5';
  sum:=0;
  for i:=1 to 4 do begin
    s2:=ExtractDelimited(i,s1,[' ']);
    TryStrToInt(s2,j);
    sum:=sum+j;
  end;
  Caption:=IntToStr(sum);
end;


derek.john.evans

  • Guest
Re: The sum of numbers in a string
« Reply #10 on: January 26, 2015, 10:49:07 am »
Im a big fan of ExtractSubstr

Code: Pascal  [Select][+][-]
  1.   function CalcSum(const S: string): integer;
  2.   var
  3.     P: integer;
  4.     LSubStr: string;
  5.   begin
  6.     Result := 0;
  7.     P := 1;
  8.     repeat
  9.       LSubStr := ExtractSubstr(S, P, [' ']);
  10.       if LSubStr = EmptyStr then
  11.       begin
  12.         Break;
  13.       end;
  14.       Result += StrToInt(LSubStr);
  15.     until False;
  16.   end;  
  17.  
« Last Edit: October 02, 2015, 03:38:39 am by Geepster »

User137

  • Hero Member
  • *****
  • Posts: 1791
    • Nxpascal home
Re: The sum of numbers in a string
« Reply #11 on: January 26, 2015, 11:41:49 am »
There's also a fun hack if you can use files:
Code: [Select]
var F: Text;
    n: integer;
begin
  assignfile(F, 'temp.txt');
  rewrite(F);
  writeln(F, '150 20 100 10 1');
  closefile(F);
  // Start reading file (alternatively use seek to beginning somehow)
  assignfile(F, 'temp.txt');
  reset(F);
  while not eof(F) do begin
    read(F, n); // Read() automatically cuts numbers on spaces
    writeln(n); // Use the number some way
  end;
  closefile(F);
end;

BeniBela

  • Hero Member
  • *****
  • Posts: 908
    • homepage
Re: The sum of numbers in a string
« Reply #12 on: January 26, 2015, 12:16:12 pm »
I would use my Internet Tools.

Code: [Select]
   uses simpleinternet;
   process('<html>150 20 100 10 1</html>', 'sum(tokenize(/, " ")!xs:integer(.))').toInt64

shortest so far

Ocye

  • Hero Member
  • *****
  • Posts: 518
    • Scrabble3D
Re: The sum of numbers in a string
« Reply #13 on: January 26, 2015, 01:06:26 pm »
One more  :D

Code: [Select]
uses math;

function SumString(aString:string):integer;
var
  i,z:integer;
begin
  z:=0;
  for i:=length(aString) downto 1 do
  if aString[i]<>' ' then
  begin
    Result+=StrToInt(aString[i])*10**z;
    inc(z);
  end else
    z:=0;
end;
Lazarus 1.7 (SVN) FPC 3.0.0

Bart

  • Hero Member
  • *****
  • Posts: 5290
    • Bart en Mariska's Webstek
Re: The sum of numbers in a string
« Reply #14 on: January 26, 2015, 07:13:14 pm »
Shortest yet?
Code: [Select]
  Result := Round(QuickEvaluate(StringReplace(S,#32,'+',[rfReplaceAll]),[],[]));

Bart

 

TinyPortal © 2005-2018