I\'m making a simple calculator where you type values into an edit box. I need to split the string into a number of arrays depending on how many *+-/ there are in the sum fo
Here's a function which may help you on the way.
It breaks down an input string into an array of sub-strings, based upon a provided set of pre-defined character sets.
It will give you an array of strings, which will be ["22", "+", "22", "*", "22", "-", "22", "/", "22"].
From there on you'll have to identify the numbers and the operators, and you'll have to group and execute the calculations according to the rules for operator precedence.
TCharSet = Set of Char;
TStringArray = Array of String;
function GetSubStrings(InputString: String; CharacterSets: Array of TCharSet): TStringArray;
// Get Sub-strings
var
Index: Integer;
Character: Char;
SubString: String;
SubStringArray: TStringArray;
CharacterSetIndex: Integer;
PreviousCharacterSetIndex: Integer;
begin
// Get
SubString := '';
SetLength(SubStringArray, 0);
PreviousCharacterSetIndex := -1;
for Index := 1 to Length(InputString) do
begin
// Character
Character := InputString[Index];
// Character Set Index
CharacterSetIndex := GetCharacterSet(Character, CharacterSets);
// Add
if (CharacterSetIndex = PreviousCharacterSetIndex) or (Index = 1) then
// Add Character to SubString
SubString := SubString + Character
else
begin
// Add SubString To SubString Array
SetLength(SubStringArray, Length(SubStringArray) + 1);
SubStringArray[Length(SubStringArray) - 1] := SubString;
// New SubString
SubString := Character;
end;
// Previous Character Set Index
PreviousCharacterSetIndex := CharacterSetIndex;
// Add last SubString
if Index = Length(InputString) then
begin
// Add SubString To SubString Array
SetLength(SubStringArray, Length(SubStringArray) + 1);
SubStringArray[Length(SubStringArray) - 1] := SubString;
end;
end;
// Result
Result := SubStringArray;
end;
function GetCharacterSet(Character: Char; CharacterSets: Array of TCharSet): Integer;
// Get Character Set
var
Index: Integer;
CharacterSet: TCharSet;
begin
// Get
Result := -1;
for Index := 0 to Length(CharacterSets) - 1 do
begin
// Character Set
CharacterSet := CharacterSets[Index];
// Check
if Character in CharacterSet then
begin
// Result
Result := Index;
// Break
Break;
end;
end;
end;