views:

21

answers:

2

I have a string Alpha 2 from which I need to extract the integer portion i.e. 2.

This is a quick and dirty project and I'm not currently interested in learning Pascal. All I need is a quick answer!

A: 
var
  sub: string;
  i: Integer;
begin
  sub := Copy('Alpha 2', 7, 1);
  i := StrToInt(sub);

-

const
  str = 'Alpha 2';
var
  i: Integer;
begin
  i := StrToInt(str[7]);

-

var
  str: string;
  sub: string;
  spc: Integer;
  i: Integer;
begin
  str := 'Alpha 257';
  spc := Pos(' ', str);
  sub := Copy(str, spc + 1, Length(str) - spc);
  i := StrToInt(sub);

There's also StrToIntDef if you don't want an exception to be raised when the argument is not an integer.

Sertac Akyuz
I am going with your third suggestion.
Icode4food
If using Free Pascal you might want to use strutils.rpos (pos from the rear end of the string). It will also survive if the text in front of the number contains a space.
Marco van de Voort
+1  A: 

For a method that searches the first number in a string and returns it as an integer, use the following code. It will either return a positive integer value or -1 if no number was found in the string.

function IntegerInString(s: string) : integer;
var i, state, startPos, endPos : integer;
begin
  state := 0;
  startPos := -1;
  endPos := Length(s);
  for i := 1 to Length(s) do
  begin
    if ((s[i] >= '0') and (s[i] <= '9') then
    begin
      if state = 0 then startPos := i;
      state := 1;
    end else
      if state = 1 then
      begin
        endPos := i;
        break;
      end;
    end;
  end;
  if startPos > -1 then
    result := IntToStr(Copy(s, startPos, endPos))
  else
    result := -1;
end;
schnaader