Articles   Members Online:
-Article/Tip Search
-News Group Search over 21 Million news group articles.
-Delphi/Pascal
-CBuilder/C++
-C#Builder/C#
-JBuilder/Java
-Kylix
Member Area
-Home
-Account Center
-Top 10 NEW!!
-Submit Article/Tip
-Forums Upgraded!!
-My Articles
-Edit Information
-Login/Logout
-Become a Member
-Why sign up!
-Newsletter
-Chat Online!
-Indexes NEW!!
Employment
-Build your resume
-Find a job
-Post a job
-Resume Search
Contacts
-Contacts
-Feedbacks
-Link to us
-Privacy/Disclaimer
Embarcadero
Visit Embarcadero
Embarcadero Community
JEDI
Links
How to Pull Digits Out of String to Sum Them Turn on/off line numbers in source code. Switch to Orginial background IDE or DSP color Comment or reply to this aritlce/tip for discussion. Bookmark this article to my favorite article(s). Print this article
28-Nov-02
Category
Object Pascal-Strings
Language
Delphi 2.x
Views
49
User Rating
No Votes
# Votes
0
Replies
0
Publisher:
DSP, Administrator
Reference URL:
DKB
			Author: Jonas Bilinkevicius

How do I pull out every second digit from a string and sum them?

Answer:

This is a rather unusual question, but it's not that hard to accomplish.

What must iterate through each character of the string and "grab" the digits whose 
position is a multiple of two (2). There are a couple of ways to do this, but I 
took what I felt was the easier route. Since this is more or less a binary problem, 
setting a Boolean value with each iteration works nicely. Here's the logic:

For all "odd" positions, set Boolean value to False;
For all "even" positions, set Boolean value to True;
If the Boolean value is true, grab that character and add it to a temporary buffer.
Iterate through the buffer, and convert each character to an Integer while adding 
the converted value to an integer variable.

Here's the code that accomplishes the above:
1   
2   function AddEvenOrOddChars(S: string; OddOrEven: Boolean): Integer;
3   var
4     I: Integer;
5     evn: Boolean;
6     buf: string;
7   begin
8     Result := 0;
9   
10    {If OddOrEven was passed as True, then the all odd positions
11     will be grabbed and summed. If False, then all even positions
12     will be grabbed and summed.}
13    evn := EvenOdd;
14  
15    {First grab the even position characters}
16    for I := 1 to Length(S) do
17    begin
18      if evn then
19        buf := buf + S[I];
20  
21      {Set boolean to its opposite regardless of its current value.
22       If it's currently true, then we've just grabbed a character.
23       Setting it to False will make the program skip the next one.}
24      evn := not evn;
25    end;
26  
27    {Now, iterate through the buffer variable to add up the individual
28     values}
29    for I := 1 to Length(buf) do
30      Result := Result + StrToInt(buf[I]);
31  end;


			
Vote: How useful do you find this Article/Tip?
Bad Excellent
1 2 3 4 5 6 7 8 9 10

 

Advertisement
Share this page
Advertisement
Download from Google

Copyright © Mendozi Enterprises LLC