Autor Beitrag
volvox
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 112

WIN XP
Delphi 7 Personal
BeitragVerfasst: Fr 23.11.07 14:10 
Hi,

ich möchte gerne einen String in mehrere Teile zerstückeln. Bei diesem String handelt es sich um einen Funktionsterm wie 4x²+3x+7. Ich möchte als Strings 4x² und 3x und 7 auslesen. Grundsätzlich halte ich dafür eine Stringlist mit CommaText für geeignet, aber ich will, dass die Rechenzeichen + und - und eben nicht Komma oder Leerzeichen, die Grenzen markieren.

Hat da jemand ne Idee?
BenBE
ontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic starofftopic star
Beiträge: 8721
Erhaltene Danke: 191

Win95, Win98SE, Win2K, WinXP
D1S, D3S, D4S, D5E, D6E, D7E, D9PE, D10E, D12P, DXEP, L0.9\FPC2.0
BeitragVerfasst: Fr 23.11.07 14:18 
Wenn Du damit rechnen willst, solltest Du Dir mal Mathe-Parser anschauen.

Alternativ: Du kannst bei der Stringlist den Separator einstellen.

Ferner: Schau dich hier mal nach Explode \ Split um.

_________________
Anyone who is capable of being elected president should on no account be allowed to do the job.
Ich code EdgeMonkey - In dubio pro Setting.
volvox Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 112

WIN XP
Delphi 7 Personal
BeitragVerfasst: Fr 23.11.07 14:32 
Danke, das mit dem Seperator sieht gut aus, aber alles was ich gefunden hab sah unheimlich kompliziert aus. Kannst du mir da vieleicht ein kurzes Beispiel posten. Nur irgendwas wo das Programm einen String mit nem + in der Mitte in zwei Teile teilt?
volvox Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 112

WIN XP
Delphi 7 Personal
BeitragVerfasst: Fr 23.11.07 14:57 
In der Delphi Hilfe habe ich "Delimiter" gefunden. Kann mir das ansonsten jemand ganz simpel erklären wie ich das verwenden? Ohne Beispiel versteh ichs nicht so wirklich.

Ich hab Delimeter als "char" deklariert und

Delimeter:= '+' ;

zugewiesen (geht das eigentlich auch mit zwei verschiedenen zeichen, also hier "+" und "-" ?)

Wie wende ich die Stringlist.DelimitedText jetzt richtig an, umd den String zu teilen?
zuma
ontopic starontopic starontopic starontopic starontopic starontopic starofftopic starofftopic star
Beiträge: 660
Erhaltene Danke: 21

Win XP, Win7, Win 8
D7 Enterprise, Delphi XE, Interbase (5 - XE)
BeitragVerfasst: Fr 23.11.07 15:04 
String 'teilen' geht z.B. so:

ausblenden Delphi-Quelltext
1:
2:
TeilString1 := copy(String, 0, pos('+', String)-1);
TeilString2 := copy(String, pos('+', String)+1, length(String));


eine Stringlist mit mehreren Delimitern gleichzeitig geht so weit ich weiss nicht.

_________________
Ich habe nichts gegen Fremde. Aber diese Fremden sind nicht von hier! (Methusalix)
Warum sich Sorgen ums Leben machen? Keiner überlebts!
volvox Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 112

WIN XP
Delphi 7 Personal
BeitragVerfasst: Fr 23.11.07 15:16 
Da stimmt was nicht. Das gibt Fehlermeldungen:

[Fehler] Unit1.pas(63): '(' erwartet, aber ',' gefunden
[Fehler] Unit1.pas(63): '(' erwartet, aber ')' gefunden
[Fehler] Unit1.pas(64): Inkompatible Typen
[Fehler] Unit1.pas(64): '(' erwartet, aber ',' gefunden
[Fehler] Unit1.pas(64): '(' erwartet, aber ')' gefunden
[Fehler] Unit1.pas(64): '(' erwartet, aber ')' gefunden
[Fehler] Unit1.pas(66): Ausdruck erwartet, aber 'END' gefunden
mkinzler
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 4106
Erhaltene Danke: 13


Delphi 2010 Pro; Delphi.Prism 2011 pro
BeitragVerfasst: Fr 23.11.07 15:21 
user profile iconvolvox hat folgendes geschrieben:
In der Delphi Hilfe habe ich "Delimiter" gefunden. Kann mir das ansonsten jemand ganz simpel erklären wie ich das verwenden? Ohne Beispiel versteh ichs nicht so wirklich.

Ich hab Delimeter als "char" deklariert und

Delimeter:= '+' ;

zugewiesen (geht das eigentlich auch mit zwei verschiedenen zeichen, also hier "+" und "-" ?)

Wie wende ich die Stringlist.DelimitedText jetzt richtig an, umd den String zu teilen?

ausblenden Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
var
  sl: TStrings;
..
begin
   sl := TStringList.Create;
   sl.Delimiter := '+';
   sl.StrictDelimiter := True;
   sl.DelimitedText := '4x²+3x+7';
   ...

sl.Strings[0] = '4x²'
sl.Strings[1] = '3x'

Zitat:
Da stimmt was nicht. Das gibt Fehlermeldungen:

Ersetze mal String durch s

_________________
Markus Kinzler.
hathor
Ehemaliges Mitglied
Erhaltene Danke: 1



BeitragVerfasst: Fr 23.11.07 15:47 
Hier habe ich einen Math-Parser gefunden, den man sich für eigene Zwecke umstricken kann:

ausblenden volle Höhe Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
GPC demo program. A recursive descent parser for mathematical
  expressions using real or complex numbers.

  The code is Extended Pascal, i.e., it can be compiled with the
  `--extended-pascal' option (but also in GPC's default mode).

  Copyright (C) 1999-2006 Free Software Foundation, Inc.

  Author: Frank Heckenbach <frank@pascal.gnu.de>

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License as
  published by the Free Software Foundation, version 2.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; see the file COPYING. If not, write to
  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  Boston, MA 02111-1307, USA.

  As a special exception, if you incorporate even large parts of the
  code of this demo program into another program with substantially
  different functionality, this does not cause the other program to
  be covered by the GNU General Public License. This exception does
  not however invalidate any other reasons why it might be covered
  by the GNU General Public License. }

program ParserDemo (Input, Output);

{ This parser understands the following grammar:

  CONSTANT = "e" | "pi" | "i" | POSITIVE_REAL_NUMBER | POSITIVE_REAL_NUMBER "°" | "$" POSITIVE_HEXADECIMAL_INTEGER_NUMBER
  FUNCTION = "abs" | "sqrt" | "sin" | "cos" | "tan" | "cot" | "arctan" | "exp" | "ln"
  ATOM1 = "(" EXPR ")" | CONSTANT | ATOM1 "!"
  ATOM = ATOM1 | FUNCTION ATOM
  FACTOR = ATOM | FACTOR "^" ATOM
  EXPR1 = FACTOR | EXPR1 "*" FACTOR | EXPR1 FACTOR (not starting with numeric constant) | EXPR1 "/" FACTOR
  EXPR = EXPR1 | EXPR "+" EXPR1 | EXPR "-" EXPR1 | "-" EXPR1 }


{ LoCase (even a version with NLS), Frac and Pi are built into GPC,
  but deactivated when compiling with `--extended-pascal'. }


type
  TString = String (4096);

const
  Pi = 3.1415926535897932384626433832795028841971693993751;

function LoCase (ch: Char): Char;
begin
  if ch in ['A' .. 'Z'] then
    LoCase := Succ (ch, Ord ('a') - Ord ('A'))
  else
    LoCase := ch
end;

function Frac (x: Real): Real;
var i: Real;
begin
  i := Round (x);
  if Abs (i) > Abs (x) then
    if i < 0 then
      i := i + 1
    else
      i := i - 1;
  Frac := x - i
end;

procedure ProcessExpr;

label 99;

  function Real2Integer (x: Real; var i: Integer): Boolean;
  const Delta = 1e-10;
  begin
    if (Abs (x) <= MaxInt) and (Abs (x - Round (x)) <= Delta * Abs (x)) then
      begin
        i := Round (x);
        Real2Integer := True
      end
    else
      Real2Integer := False
  end;

  function Real2String (x: Real) = s: TString;
  var i: Integer;
  begin
    if Real2Integer (x, i) then
      WriteStr (s, i)
    else
      WriteStr (s, x : 0 : 20)
  end;

  function Complex2String (z: Complex) = s: TString;
  begin
    s := Real2String (Re (z));
    if Im (z) > 0 then s := s + ' +';
    if Abs (Im (z)) >= MinReal then s := s + ' ' + Real2String (Im (z)) + ' * i'
  end;

  procedure Skip;
  begin
    while not EOF and not EOLn and (Input^ = ' ') do Get (Input);
    if EOF (Input) then Input^ := ' '
  end;

  procedure Expect (ch: Char);
  begin
    Skip;
    if Input^ <> ch then
      begin
        WriteLn ('`', ch, ''' expected');
        goto 99
      end;
    Get (Input)
  end;

  function Expr: Complex;

    function Atom: Complex;
    const
      MaxFactorial = 170;
      MaxFNames = 12;
    var
      FNames: array [1 .. MaxFNames] of String (6) value
        [1: 'e'; 2: 'pi'; 3: 'i';
         4: 'abs'; 5: 'sqrt'; 6: 'sin'; 7: 'cos'; 8: 'tan'; 9: 'cot';
         10: 'arctan'; 11: 'exp'; 12: 'ln'];
      f: TString;
      n, i: Integer;
      c: Integer;
      r: Real;
      z: Complex;
      FactorialAllowed: Boolean;
    begin
      Skip;
      FactorialAllowed := True;
      case LoCase (Input^) of
        '0' .. '9',
        '.'       : begin
                      Read (r);
                      z := r;
                      Skip;
                      if Input^ = '°' then
                        begin
                          z := z * Pi / 180;
                          Get (Input)
                        end
                    end;
        '$'       : begin
                      Read (c);
                      z := c
                    end;
        '('       : begin
                      Expect ('(');
                      z := Expr;
                      Expect (')')
                    end;
        'a' .. 'z': begin
                      f := '';
                      while not EOF (Input) and (LoCase (Input^) in ['a' .. 'z']) do
                        begin
                          f := f + LoCase (Input^);
                          Get (Input)
                        end;
                      i := MaxFNames;
                      while (i > 0) and (f <> FNames[i]) do i := i - 1;
                      if i = 0 then
                        begin
                          WriteLn ('Unknown function `', f, '''');
                          goto 99
                        end;
                      case i of
                        1: z := Exp (1);
                        2: z := Pi;
                        3: z := Cmplx (0, 1);
                        otherwise
                          FactorialAllowed := False;
                          z := Atom;
                          case i of
                             4: z := Abs (z);
                             5: z := SqRt (z);
                             6: z := Sin (z);
                             7: z := Cos (z);
                             8: z := Sin (z) / Cos (z);
                             9: z := Cos (z) / Sin (z);
                            10: z := ArcTan (z);
                            11: z := Exp (z);
                            12: z := Ln (z);
                          end
                      end
                    end;
        otherwise
          WriteLn ('Parse error.');
          goto 99
      end;
      if FactorialAllowed then
        begin
          Skip;
          while Input^ = '!' do
            begin
              if (Abs (Im (z)) < MinReal) and Real2Integer (Re (z), n) and (n >= 0) and (n <= MaxFactorial) then
                begin
                  r := 1;
                  for i := 2 to n do r := i * r;
                  z := r
                end
              else
                begin
                  WriteLn ('Argument of `!'' must be an integer between 0 and ', MaxFactorial, '.');
                  goto 99
                end;
              Get (Input);
              Skip
            end
        end;
      Atom := z
    end;

    function Factor: Complex;
    var
      z, z1: Complex;
      f: Boolean;
    begin
      z := Atom;
      repeat
        Skip;
        f := True;
        case Input^ of
          '^': begin
                 Get (Input);
                 z1 := Atom;
                 if z <> 0 then
                   z := Exp (z1 * Ln (z))
                 else if z1 = 0 then
                   z := 1
               end;
          otherwise f := False
        end
      until not f;
      Factor := z
    end;

    function Expr1: Complex;
    var
      z: Complex;
      f: Boolean;
    begin
      z := Factor;
      repeat
        Skip;
        f := True;
        case LoCase (Input^) of
          '*': begin
                 Get (Input);
                 z := z * Factor
               end;
          '/': begin
                 Get (Input);
                 z := z / Factor
               end;
          '(', 'a' .. 'z': z := z * Factor;
          otherwise f := False
        end
      until not f;
      Expr1 := z
    end;

  var
    z: Complex;
    s, f: Boolean;
  begin
    Skip;
    s := False;
    while Input^ in ['+', '-'] do
      begin
        if Input^ = '-' then s := not s;
        Get (Input);
        Skip
      end;
    z := Expr1;
    if s then z := - z;
    repeat
      Skip;
      f := True;
      case Input^ of
        '+': begin
               Get (Input);
               z := z + Expr1
             end;
        '-': begin
               Get (Input);
               z := z - Expr1
             end;
        otherwise f := False
      end
    until not f;
    Expr := z
  end;

begin
  WriteLn (Complex2String (Expr));
  if not EOLn then WriteLn ('Superfluous characters after the expression');
99:
  ReadLn
end;

begin
  WriteLn ('Enter expressions consisting of');
  WriteLn ('- real numbers, using the `e'' notation,');
  WriteLn ('- the constants `e'', `pi'', `i'',');
  WriteLn ('- the operators `+'', `-'', `*'', `/'', `^'',');
  WriteLn ('- the functions `abs'', `sqrt'', `sin'', `cos'', `tan'', `cot'', `arctan'', `exp'', `ln'',');
  WriteLn ('- parentheses.');
  WriteLn;
  WriteLn ('Note: Due to the `e'' notation, there is a problem with terms like `2e'' which');
  WriteLn ('will be interpreted as `2*10^...''. If you mean `2*e'', write it this way, or');
  WriteLn ('as `2 e''. Expressions like `3e+4+5'' can be confusing, but are interpreted');
  WriteLn ('according to the `e'' notation (i.e., this expression equals 30005).');
  WriteLn;
  WriteLn ('Enter an empty line when finished.');
  while not EOLn do ProcessExpr
end.
volvox Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 112

WIN XP
Delphi 7 Personal
BeitragVerfasst: Fr 23.11.07 16:00 
StrictDelimiter ?

Ist das so richtig?

Delphi meldet das als unbekannten Bezeichner
mkinzler
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 4106
Erhaltene Danke: 13


Delphi 2010 Pro; Delphi.Prism 2011 pro
BeitragVerfasst: Sa 24.11.07 19:19 
Diese Eigenschaft können nur neuerer Delphiversionen (glaube ab D10)

_________________
Markus Kinzler.


Zuletzt bearbeitet von mkinzler am Sa 24.11.07 19:22, insgesamt 1-mal bearbeitet
BenBE
ontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic starofftopic star
Beiträge: 8721
Erhaltene Danke: 191

Win95, Win98SE, Win2K, WinXP
D1S, D3S, D4S, D5E, D6E, D7E, D9PE, D10E, D12P, DXEP, L0.9\FPC2.0
BeitragVerfasst: Sa 24.11.07 19:32 
Bei älteren Versionen einfach ignorieren.

_________________
Anyone who is capable of being elected president should on no account be allowed to do the job.
Ich code EdgeMonkey - In dubio pro Setting.
gispos
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 94

WIN 7
XE10, D2007
BeitragVerfasst: Sa 24.11.07 20:23 
user profile iconvolvox hat folgendes geschrieben:
Hi,

ich möchte gerne einen String in mehrere Teile zerstückeln. Bei diesem String handelt es sich um einen Funktionsterm wie 4x²+3x+7. Ich möchte als Strings 4x² und 3x und 7 auslesen. Grundsätzlich halte ich dafür eine Stringlist mit CommaText für geeignet, aber ich will, dass die Rechenzeichen + und - und eben nicht Komma oder Leerzeichen, die Grenzen markieren.

Hat da jemand ne Idee?


Versuch mal dies, BreakChars kann angepasst werden.
ausblenden Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
procedure FillList(List: TStringList; const str: String);
const
  BreakChars = ['+', '-'];
var
  S: String;
  i: Integer;
begin
  S:= str;
  For i:= 1 to Length(S) do
    if (S[i] in BreakChars) then S[i]:= ',';
  List.DelimitedText:= S;
end;

Als Nachtrag noch eine variablere Procedur.
ausblenden Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
type
  TBreakChars= Set of Char;

procedure SplitStringToTStrings(List: TStrings; const str: String; Breaks: TBreakChars);
var
  S: String;
  i: Integer;
begin
  S:= str;
  For i:= 1 to Length(S) do
    if (S[i] in Breaks) then S[i]:= ',';
  List.DelimitedText:= S;
end;

Aufruf dann so:
ausblenden Delphi-Quelltext
1:
  SplitStringToTStrings(StringList,'4x²+3x+76-8', ['+' , '-']);					


Gruß gispos
volvox Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 112

WIN XP
Delphi 7 Personal
BeitragVerfasst: So 25.11.07 20:51 
Die zulentzt genannte Möglichkeit ist sicherlich gut, aber gibt es auch eine Möglichkeit das Ganze mit Delimiter zu lösen und Delimiter ZWEI Zeichen zuzuornen. Also sowas wie

Eingabestring.Delimiter := '+' and '-';


Und dann --> Eingebeterm.DelimitedText
mkinzler
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 4106
Erhaltene Danke: 13


Delphi 2010 Pro; Delphi.Prism 2011 pro
BeitragVerfasst: So 25.11.07 20:56 
Nein, wird so nicht gehen.

_________________
Markus Kinzler.
volvox Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 112

WIN XP
Delphi 7 Personal
BeitragVerfasst: So 25.11.07 21:19 
Irgendeine andere Idee mit Delimiter?
mkinzler
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 4106
Erhaltene Danke: 13


Delphi 2010 Pro; Delphi.Prism 2011 pro
BeitragVerfasst: So 25.11.07 21:25 
Zuerst alle Trennzeichen durch eines ersetzen.

_________________
Markus Kinzler.
ub60
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 766
Erhaltene Danke: 130



BeitragVerfasst: So 25.11.07 21:56 
Ersetze zuerst (AnsiReplaceStr) alle "+" durch "#+" und '-" durch"#-". Nimm dann "#" als Delimiter. Somit hast Du auch die Vorzeichen. Das hatten alle bisherigen Varianten nicht. Sollte Dich das "+" stören, ersetze einfach "+" durch"#".

ub60
volvox Threadstarter
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starofftopic star
Beiträge: 112

WIN XP
Delphi 7 Personal
BeitragVerfasst: So 25.11.07 22:46 
Das Idee hatte ich auch schon, aber hab sie wieder verworfen, weil ich dachte, es sei egal durch welche Zeichen ich die Vorzeichen ersetzt. Aber du hast Recht. Die Idee ist genial, weil ich so meine Vorzeichen weiterverwenden kann. Danke !!!!!!
gispos
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 94

WIN 7
XE10, D2007
BeitragVerfasst: Do 29.11.07 17:51 
user profile iconvolvox hat folgendes geschrieben:
Die zulentzt genannte Möglichkeit ist sicherlich gut, aber gibt es auch eine Möglichkeit das Ganze mit Delimiter zu lösen und Delimiter ZWEI Zeichen zuzuornen. Also sowas wie Eingabestring.Delimiter := '+' and '-';
Und dann --> Eingebeterm.DelimitedText


Schau mal genau mein Posting vom Sa 24.11.07 20:23 an, "Breaks" sind Delimiter,
und da kannst Du Eingeben was Du willst. eg. ['+','-','%','*']

Gruß gispos