PROGRAM C++ STRING
#include <iostream>
#include <string>
using namespace std;
int main ()
{
char *line = "short line for testing";
// with no arguments
string s1;
s1 = "Anatoliy";
cout << "s1 is: " << s1 << endl;
// copy constructor
string s2 (s1);
cout << "s2 is: " << s2 << endl;
// one argumen
string s3 (line);
cout << "s3 is: " << s3 << endl;
// first argumen C string
// second number of characters
string s4 (line,10);
cout << "s4 is: " << s4 << endl;
// 1 - C++ string
// 2 - start position
// 3 - number of characters
string s5 (s3,6,4); // copy word 'line' from s3
cout << "s5 is: " << s5 << endl;
// 1 - number characters
// 2 - character itself
string s6 (15,'*');
cout << "s6 is: " << s6 << endl;
// 1 - start iterator
// 2 - end iterator
string s7 (s3.begin(),s3.end()-5);
cout << "s7 is: " << s7 << endl;
// you can instantiate string with assignment
string s8 = "Anatoliy";
cout << "s8 is: " << s8 << endl;
return 0;
}
PROGRAM PASCAL STRING
Uses
crt;
Const
Line = ' / 23 / 478 /8/ 8z7 / 2.3 /xvt/ 987 / 5996 ';
Sep = '/';
Space = ' ';
Digits: Set of Char = ['0'..'9'];
Var
X: String;
N, Error, Sum: Integer;
Piece: String;
Loc: Integer;
Begin
Clrscr;
X := Line;
X := X + Sep; { Ensure that X ends with a / }
Sum := 0;
While Length(X) > 0 Do
Begin
{ Delete the lead spaces from the string X }
While Pos(Space, X) = 1 Do
Delete(X, 1, 1);
{ Delete any lead non-digit characters. Yes, this would also
delete lead spaces - but this is only an example! }
While NOT(X[1] in Digits) AND (Length(X) >= 1) Do
Delete(X, 1, 1);
{ Find the location of the first / in X; copy all characters
in X from the beginning of X up to and including the / into
the string Piece; delete these characters from the beginning of X }
Loc := Pos(Sep, X);
Piece := COPY(X, 1, Loc);
Delete(X, 1, Loc);
{ Count backwards from the end of Piece until a digit is found }
While NOT(Piece[Loc] in Digits) AND (Loc > 0) Do
Loc := Loc - 1;
{ Make a new copy of Piece which consists of characters from the
beginning of Piece to the place where a digit was located; it's
possible that Loc = 0 if no digits were encountered in Piece
(for example, if the field consists only of spaces or of non-
digit characters) }
Piece := COPY(Piece, 1, Loc);
{ The following code can be used to see how Piece is formed for
each field separated by /
If Length(Piece) > 0
Then Writeln('piece = ''', piece, '''')
Else Writeln('piece = null'); }
{ Convert Piece to an integer value N }
VAL(Piece, N, Error);
{ If Piece is null or contains garbage, ignore N (that is, when
Error > 0); otherwise, add N to Sum and print N }
If Error = 0
Then
Begin
Writeln(N :4);
Sum := Sum + N
End;
End; { WHILE }
Writeln('----');
Writeln(Sum :4);
Readln;
End.
Tidak ada komentar:
Posting Komentar